在perl中访问数组的各个元素的问题

时间:2013-12-07 17:56:09

标签: perl

我在解析数组时遇到了麻烦。我用过

print Dumper($variable)

获取

$VAR1 = [
          'joshn',
          'taylor'
        ];

我需要得到josh和taylor的个人元素。我怎样才能获得它?

2 个答案:

答案 0 :(得分:2)

# get last element 
my $last = $variable->[-1];

# get first element
my $first = $variable->[0]; # cryptic equivalent: $$variable[0] (don't use it) 
# get second element
my $second = $variable->[1]; # also $$variable[1]

# same effect as above
my ($first, $second) = @{$variable}; # or @$variable for short

答案 1 :(得分:0)

我猜$variable是数组的引用,然后是

for(@{$variable}) {
    print $_, "\n"
}

编辑:访问数组中的最后一个元素:

my @array = @{$variable};
print $array[$#array];