PBP: 059 Array Indices

The PBP reminds us that we can use negative indexes to access arrays in reverse, instead of having to do calculations for it.  It suggests several useful reasons, including readability and getting the interpreter to complain in some cases instead of silently doing the wrong thing.  I don’t feel that strongly about this suggestion, but do follow it.

Negative indexes access an array from the end.  Sometimes I don’t think this is very well known, and I have been known to use it as an interview question to try and plumb the depths of the candidate’s Perl knowledge.

Other than accessing the last index with -1, I believe I have used this twice in my entire career.  Once when processing a list backwards, and once when I needed the last several items.  Today I might have done the latter with an array slice instead.

I agree with both reasons presented in the book, but haven’t found them to be that critical in real world applications.

The only problem I have doing this with perlcritic on is the actual use of the negative offsets, as they are not accepted as numbers.  I wish -1, particularly, were, both for the last element in an array and to invert the sign of a number.  Having to define constants for those is goofy.  But that’s a different practice!

One Response to “PBP: 059 Array Indices”

Leave a Reply