in reply to Ignorance Isnt Always Bliss
Perl, by default (never change the default) indexes arrays starting at 0. However Perl has a really nice trick where you can use -1 as the index for the last element in the array, -2 for the penultimate element, and so on.
The trap that bit you is that if the array is empty then there is no element at the end of the array so trying to access it using [-1] leads to an unhappy life.
Note that you can use $#array to get the index of the last element in @array. $#array will return -1 if the array is empty. @array in scalar context returns the number of elements in the array and returns 0 for an empty array.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Ignorance Isnt Always Bliss
by Baffled (Acolyte) on Feb 12, 2008 at 03:48 UTC | |
by GrandFather (Saint) on Feb 12, 2008 at 04:33 UTC | |
|
Re^2: Ignorance Isnt Always Bliss
by Anonymous Monk on Feb 12, 2008 at 07:13 UTC |