[Pdx-pm] evil @ARGV syntax

Michael G Schwern schwern at pobox.com
Tue Jul 19 12:14:03 PDT 2005

On Tue, Jul 19, 2005 at 11:05:05AM -0700, Randall Hansen wrote:
>      if( $#ARGV + 1 < 1 || $#ARGV + 1 > 2 ) {
> which seems like a complicated way of writing:
>      if( @ARGV < 1 or @ARGV > 2 ) {
> i've tested this and found it to be true.  my question is, why on  
> earth would someone write this the first way?  it's one thing not to  
> understand scalar context; it seems entirely insane to add those ones  
> before the less|greater than tests.
> am i missing an idiom?  historical reason?  does @ARGV behave oddly  
> enough in certain contexts that these gymnastics are necessary?

Lots of poorly written Perl books (which is to say most of them prior to 2000)
never clearly teach $num_things = @things.  See 
for some examples.

Adding one to $#ARGV is to make the operation more like how people think.  
Rather than think "if the index of @ARGV is less than 0 or greater than 1" 
they want to express the more natural "if I got less than 1 argument or more 
than 2".  Its also reflexive.  $#array + 1 is how folks are often taught to
get the number of elements in an array.

The ironic thing is this is all a really complicated way of saying the much
more natural:

	# if I got 1 or 2 args...
	if( @ARGV == 1 or @ARGV == 2 ) {

Michael G Schwern     schwern at pobox.com     http://www.pobox.com/~schwern
Ahh email, my old friend.  Do you know that revenge is a dish that is best 
served cold?  And it is very cold on the Internet!

More information about the Pdx-pm-list mailing list