Dollar-pound

We know that if we use the name of an array variable in scalar context, it is intepreted as its size. But sometimes we are more interested in its last index value. A other-than-perl programmer would probabily just decrease by one the array length, but this is a really not perlish way of seeing it.

Perl provides an explicit operator, dollar-pound ($#), that returns the last item index in the referenced array. I'm ashamed but I should confess I'm not so into perl to see the actual beauty of such a construct.

Given an array, for instance our usual one:
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
This way of looping on it is not considered very perlish:
for(0 .. @months -1) { print "$_: $months[$_]\n"; }
It's true that we have a reason not to use the handy for each loop - we should have used another loop variable to keep track of the current index - but that decrement on the array size is seen as lacking of beauty. It is usually considered nicer using instead the dollar-pound operator:
for(0 .. $#months) { print "$_: $months[$_]\n"; }

Chapter 3 of Beginning Perl by Simon Cozens is about arrays and associative arrays (hashes).

No comments:

Post a Comment