-1

如何获取数组的最后一个元素和当前元素?

如果我通过 [$i] 获取数组的当前元素,似乎很容易

print " Atm: ",$king->[$i]->{hit}, 

但是这对之前的元素有什么作用呢?有没有一些简单的方法来获得它?喜欢[$i-1]

" Before: ", $king->[$i-1]->{hit}, "\n";

提前致谢!

4

2 回答 2

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";
于 2013-08-19T19:02:16.197 回答
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";
于 2013-08-19T15:26:57.787 回答