Using multi-dimensional array in Perl class
I need to create a multi-dimensional array which will be passed to a class.
Here is sample code where I can reference the array elements outside of the class, but once I create a class and pass the multi-d开发者_如何学JAVAimensional array, I'm not able to reference it inside of the class.
Output:
My Array Value = 3
Can't use string ("1") as an ARRAY ref while "strict refs" in use at test.pl line 18.
package TestClass;
use strict;
sub new
{
my $class = shift;
my $self =
{
_array => shift
};
bless $self, $class;
return $self;
}
sub print
{
my ($self) = @_;
print "TestClass variable = " . @{$self->{_array}->[0]}[1] . "\n";
}
my @my_array = ();
push(@my_array, [1,2]);
push(@my_array, [3,4]);
print "My Array Value = " . @{@my_array->[1]}[0] . "\n";
my $class = new TestClass(@my_array);
$class->print;
1;
You're passing a list with two elements to your constructor, each element being one of the array refs you built.
I believe you wanted to pass an array reference containing the other two anonymous array references instead:
TestClass->new(\@my_array);
Your array de-referencing in @{@my_array->[1]}[0]
is also a little odd. This is something use warnings;
would've caught.
精彩评论