SPUG: last index array reference's referent

Doug Treder dtreder at gmail.com
Sun Jan 21 15:26:54 PST 2007


I've never thought of $#array as elegant at all, and the fact that my
left fingers curl into a painful knot to type it as Larry's way of
telling me so.  Also note that indexing into an array is much slower
than aliasing it in a foreach loop.  So my favorite idiom for this is:

my $i = 0;
foreach my $item (@$array_ref) {
   print $i++ .' ' . $item . "\n";
}

-Doug

On 1/21/07, Michael R. Wolf <MichaelRWolf at att.net> wrote:
> # If you have an array ref and don't care about the index, it's pretty
> # simple and elegant to loop over the referenced array...
>
> @season = qw(winter spring summer fall);
> $a_ref = \@season;
>
> foreach my $element ( @{$a_ref} ) {
>     # Use $element here...
>     print "$element\n";
> }
>
>
> # But if you *do* care about the index, it's neither simple, nor
> # elegant...
>
> foreach my $i ( 0 .. @{$a_ref} - 1 ) {
>     my $element = $a_ref->[$i];
>
>     # Use $i and $element here...
>     print "$i $element\n";
> }
>
>
> # Is there a more elegant way to get the equivalent of $#seasons if
> # all you have is a reference?  Somehting that would do to references
> # what $# does to arrays....
>
> foreach my $i (0 .. $#season) {
>     my $element = $season[$i];
>
>     # Use $i and $element here...
>     print "$i $element\n";
> }
>
> --
> Michael R. Wolf
>     All mammals learn by playing!
>         MichaelRWolf at att.net
>
>
> _____________________________________________________________
> Seattle Perl Users Group Mailing List
>      POST TO: spug-list at pm.org
> SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
>     MEETINGS: 3rd Tuesdays
>     WEB PAGE: http://seattleperl.org/
>


-- 

-Doug Treder
http://www.trederfamily.org


More information about the spug-list mailing list