Monday, January 3, 2011

Negative Array Indexing in Perl

Negative Array Indexing in Perl

Core Formula: $myarray[-$n] is equivalent to $myarray[scalar(@myarray) - $n]

Quick Explanation

Perl allows you to use negative indices to easily count backward from the end of an array, saving you from manually calculating the array's length.

  • $myarray[-1]: Accesses the last element of the array.
  • $myarray[-2]: Accesses the second-to-last element.
  • $myarray[-$n]: Accesses the $n$-th element from the end.

No comments: