What is the proper syntax for storing an array into a Perl hash?
I'm creating a new object like this:
TestObject->new(@array1, @array2)
My new
method looks like this:
sub new {
my $class = shift;
my $self = {};
my $self->{Array1} = shift;
my $self->{Array2} = shift;
bless($self, $class);
return $self;
}
As a simple test to access the data, I'm trying this, and then once I get it working, I can build more meaningful logic:
sub mymethod {
my $self = shift;
my $param = shift;
my $array1Value = shift(my $self->{Array1});
my $array2Value = shift(my $self->{Array2});
print $array1Value." ".$array2Value;
}
But when I call mymethod
, I get this error:
Type of arg 1 to shift must be array (not hash element) at Tests/MyObject.pm line 21, near "})"
Suggestions? I read this page on Perl data structures, but they don't have examples for creating a hash of arra开发者_StackOverflow中文版ys using arguments to a method using shift
. So my problem might be there.
When you pass arrays as parameters, they are flattened. You can pass references to them. See 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;
you have to use pointers to arrays, not arrays in this case:
TestObject->new([@array1], [@array2])
and then later
my $array1Value = shift(@{$self->{Array1}});
You're shifting an arrayref instead of an actual array.
The syntax ytou're probably looking for is:
my $array1Value = shift @{ $self->{Array1} };
my $array2Value = shift @{ $self->{Array2} };
Note how the array is dereferenced using @
.
you need to derefernece the array ref:
@{$self->{Array2}}
By the way if you are using OO I emphatically suggest you look into Moose. It will make your life much easier!
精彩评论