Walt Mankowski on 20 Jan 2011 12:31:15 -0800


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] perl question


On Thu, Jan 20, 2011 at 03:07:32PM -0500, Paul W. Roach III wrote:
> Also be careful -- using the $# modifier tells you how many elements are in
> the array, not necessarily the index of the highest element.
> 
> [proach@erwin ~]$ cat foo.pl
> #!/usr/bin/perl
> 
> my @array = ();
> 
> $array[1] = "blue";
> $array[3] = "black";
> $array[4] = "foo";
> 
> print "Array \@array has " . $#array . " elements.\n";
> print "Array \@array has an upper index of " . int(@array) . "\n";
> [proach@erwin ~]$ perl foo.pl
> Array @array has 4 elements.
> Array @array has an upper index of 5

No, you have that backwards.  $#array gives you the highest index in
@array, and @array in a scalar context (which is what you're doing by
calling int() gives you the number of elements in the array.  Since
arrays start at 0 (I know you can change this, but almost no one ever
does) $#array is always 1 less than @array.  This is true even if you
leave holes (as you did in your example) so you'd still get 4 and 5
even if you didn't put anything in $array[1] and $array[3].

Walt

Attachment: signature.asc
Description: Digital signature

___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug