Perl Postscript Problem

Paul Seamons paul at
Mon Aug 23 09:46:54 MDT 2010

  I was surprised to hear it is deprecated.  I don't use it often, but 
it is still useful.

In Perl if you have an array @foo you can find the number of elements in 
the array
in two ways:

First you can say my $n = @foo;  In a scalar context the array name 
returns the number of elements in the list.  Historically this was not 
optimized and would first return all of the elements which would then be 
counted and return a numerical value.  This has been corrected since at 
least perl 5.8.  In Perl 6 the construct will be closer to other 
languages in that you can ask for @foo.elems to get the number of 
elements in the array (everything in Perl6 will behave as an object).  
In numeric context in Perl6 @foo should still return its length as well.

Second you can say my $n = $#foo + 1;  The $# symbol requests that you 
return the index value of the last element.  This used to be the 
preferred way as it was faster.  In some rare cases it is still faster, 
but almost all of the time new code should just use @foo - 1 if they 
mean the index of the last element.

The terrible example below is actually quite lucky that it still works 
at all.  At most - it only ever should have been $#$self or $#{ $self } 
- both of which are still very ugly.  The new usage to mean what they 
were doing here code-wise would be @$self -1 .  Although I'm guessing 
without looking, any API that is exposing the last index of an array 
element as a useful value is going to be a convoluted API (I can dream 
of valid cases but most are contrived).

>>>>     return $#{@$self};
>> In this case it is. :[ $# has been deprecated for awhile now.
> This kind of syntax soup is what I dislike about Perl the most. What's the preferred method for doing this now?

More information about the PLUG mailing list