如何获取数组的最后一个和当前元素?
获取我的数组的当前元素,看起来很简单,如果我通过[$ i]
获取它print " Atm: ",$king->[$i]->{hit},
但是之前这个元素是如何工作的呢?有一些简单的方法来获得它吗?喜欢[$i-1]
?
" Before: ", $king->[$i-1]->{hit}, "\n";
提前致谢!
答案 0 :(得分:1)
答案是否定的。
假设您有匿名数组。
my $numbers = [qw(1 2 3 4 5)]; # but who said that this array is anonymous? it has pretty-labeled variable, that give you access to his elements
# however, yes, this is anonymous array. maybe. think, that yes.
print @{$numbers}; # print all elements of this anonymous array
print "\n next\n";
print @{$numbers}[0..$#{$numbers}]; # hm, still print all elements of this anonymous array?
print "\n next\n";
print $numbers->[$#$numbers]; # hm, print last element of this anonymous array?
print "\n next\n";
print ${$numbers}[-1]; # hm, really, print last element of this anonymous array?
print "\n next\n";
print $numbers->[-2]; # wow! print pre-last element!
print "\n next\n";
# here we want more difficult task: print element at $i position?
my $i = 0;
# hm, strange, but ok, print first element
print $numbers->[$i]; #really, work? please, check it!
print "\n next\n";
# print before element? really, strange, but ok. let's make... shifting!
# maybe let's try simple -1 ?
print $numbers->[$i - 1]; # work? work? please, said, that this code work!
print "\n next\n";
@$numbers = @$numbers[map{$_ - 1}(0..$#{$numbers})]; #shifting elements.
print $numbers->[$i]; #print the same element, let's see, what happens
print "\n next\n";
答案 1 :(得分:0)
使用:
#!/usr/bin/perl -w
use strict;
my @array = qw (1 2 3 4 5);
print "$array[0]\n"; # 1st element
print "$array[-1]\n"; # last element
或者你可以通过将数组的最后一个值弹出到一个新变量来实现:
push @array, my $value = pop @array;
print "$value\n";