-1

How can I get the last and current element of an array?

Getting the current element of my array, seems pretty easy, if i get it via [$i]

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

But how does this work for the element before? Is there some simple way to get it? Like [$i-1]?

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

Thanks in advance!

TLP
  • 66,756
  • 10
  • 92
  • 149

2 Answers2

1

Answer is NO.

suppose, you have anonymous array.

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";
gaussblurinc
  • 3,642
  • 9
  • 35
  • 64
0

Use:

#!/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

Or you could do it by popping the last value of the array onto a new variable:

push @array, my $value = pop @array;

print "$value\n";
fugu
  • 6,417
  • 5
  • 40
  • 75