Tuesday, May 5, 2009

Perl: print last element from array

Share at Facebook

We know an array needs to access with positive integer. But scripting language like Perl, you can access it using Negative number. A negative number means from last. If you use -5, it will give you the 5th element from the array from last. Remember, for negative index, the index start from 1. Means -1 = last index, -2 = second last, and so on.

This example will help you to understand much more clearly.

## initial array
my @array = qw(1 2 3 4 5 6 7 8 9 10);

## print last element from array
print $array[-1] , "\n";

## print second last element from array
print $array[-2] , "\n";

At above example, there are 10 elements. if you provide a negative number which is greater than the total number of elements, you'll get error Use of uninitialized value in print at temp.pl line 2., for example the below code will generate such error.

print $array[-11] , "\n";

The reason is the array doesn't have 11 elements in total.

No comments: