如何将数组传递给类?

时间:2018-03-10 07:09:33

标签: perl

我对如何将数组传递到包中感到困惑:

主要代码

use Person;
my @array=(1,2,3);
$object = new Person( "Mohammad", "Saleem",\@array);

package Person;
sub new
{
    my $class = shift;
    my $self = { 
        _firstName => $_[0],
        _lastName  => $_[1],
        _array  => $_[2],
    };      
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "Array is $self->{_array}\n";

    bless $self, $class;
    return $self;
}

打印数组的结果为空。如何修复代码以获取数组的值?

First Name is Mohammad
Last Name is Saleem
Array is

1 个答案:

答案 0 :(得分:-1)

$self->{_array}是对array =>的引用derefference it。

my @array = qw(a b c);
$self->{_array} = \@array;    

print "Array is @{$self->{_array}}\n";
print " foreach: $_\n" foreach @{$self->{_array}};
for( my $i=0; $i<=$#{$self->{_array}}; $i++) {
  print " for: $i:  $self->{_array}[$i]\n";
}