将数组存储到Perl哈希中的正确语法是什么?

Tho*_*ens 1 arrays perl hash data-structures

我正在创建一个这样的新对象:

TestObject->new(@array1, @array2)
Run Code Online (Sandbox Code Playgroud)

我的new方法看起来像这样:

sub new {
  my $class = shift;
  my $self = {};

  my $self->{Array1} = shift;
  my $self->{Array2} = shift;

  bless($self, $class);

  return $self;
}
Run Code Online (Sandbox Code Playgroud)

作为访问数据的简单测试,我正在尝试这个,然后一旦我开始工作,我就可以构建更有意义的逻辑:

sub mymethod {
  my $self = shift;
  my $param = shift;

  my $array1Value = shift(my $self->{Array1});
  my $array2Value = shift(my $self->{Array2});

  print $array1Value." ".$array2Value;
}
Run Code Online (Sandbox Code Playgroud)

但是当我打电话时mymethod,我收到了这个错误:

Type of arg 1 to shift must be array (not hash element) at Tests/MyObject.pm line 21, near "})"
Run Code Online (Sandbox Code Playgroud)

建议?我在Perl数据结构上阅读了这个页面,但它们没有使用参数创建数组哈希的示例shift.所以我的问题可能就在那里.

Wil*_*ell 5

将数组作为参数传递时,它们会被展平.您可以传递对它们的引用.见perlsub

#!/usr/bin/env perl

package foo;

sub new {
    my $class = shift;
    my $self = {};

    $self->{Array1} = shift;
    $self->{Array2} = shift;

    bless($self, $class);

    return $self;
}

sub mymethod {
  my $self = shift;
  my $param = shift;

  my $array1Value = shift( @{$self->{Array1}} );
  my $array2Value = shift( @{$self->{Array2}} );

  print "$array1Value $array2Value\n";
}

package main;

my @a = ( 0, 1, 2);
my @b = ( 3, 4, 5);
my $o = new foo( \@a, \@b );;
$o->mymethod;
Run Code Online (Sandbox Code Playgroud)

  • Minor nit:不要在Perl中使用间接对象语法(new Foo而不是更好的Foo-> new).参看 http://perldoc.perl.org/perlobj.html#Indirect-Object-Syntax (3认同)