TCLUG Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [TCLUG:19613] [OT] perl boogage?



>
> I ran across a curiosity in a perl program today, which can be explained
> like so:
>
>  @ITEMS = (0, 1, 2);
>  print @#ITEMS;                # prints "2";
>
>
> So if you wedge a '#' into an array name, it means "the length of the array,
> less 1" (Oh, of course!). The guy was using it as a loop limit.
>
> I couldn't find anything on this in any of the perl books I own... is this a
> documented feature of the language, or just a fetid schbat of boogage?

It's documented, all right...  That is, if you mean "$#ITEMS", not "@#ITEMS".
It's the index of the last item in the array @ITEMS.  It's in Programming Perl,
the Pocket Reference, and the manpages:

	 Scalar values are always named with '$', even when
       referring to a scalar that is part of an array.  It works
       like the English word "the".  Thus we have:

           $days               # the simple scalar value "days"
           $days[28]           # the 29th element of array @days
           $days{'Feb'}        # the 'Feb' value from hash %days
           $#days              # the last index of array @days

I've never actually figured out how it's useful though -- loops are better
written with "for (@ITEMS)" or "foreach $item (@ITEMS)", the last item itself is
more easily accessed as "$ITEMS[-1]", and of course there's the ever-handy
"scalar(@ITEMS)"

I suppose if for some reason you were using an array in a hashlike way it would
be useful -- suppose every day it rained you did "$rainy[$today_date]++", then
$#rainy would be the most recent date on which rain had fallen...  But that's a
bit of a reach.