2013-08-19 80 views
-2

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

让我的数组的当前元素,似乎很容易,如果我通过得到它[$ i]

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

但这是如何工作之前的元素?有一些简单的方法来获得它?像[$i-1]

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

在此先感谢!

+1

你试过了吗?发生了什么? – Toto

+1

最后一个元素散列索引[-1] – Suic

+0

@Suic:但似乎清楚的问题是真的要求“以前的元素”,而不是“最后一个元素” – ysth

回答

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"; 
0

答案是否定的。

假设你有匿名数组。

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"; 
相关问题