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.所以我的问题可能就在那里.
将数组作为参数传递时,它们会被展平.您可以传递对它们的引用.见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)