global special variable for array index?

Bobby Kleemann rkleeman at
Thu Apr 20 18:33:35 CDT 2000

On Thu, 20 Apr 2000, Bruce Timberlake wrote:

> ~sdpm~
> > Isn't there a global special variable for the list index when you're
> > stepping through a list with a for (= foreach) statement?  For
> > example, I frequently have code like this:
> > 
> > my $index;
> > for my $element (@list)
> > {
> >     # some processing on $element
> >     $index++;
> > }
> > 
> > It would be much easier if there were a global special variable (like
> > $. for line numbers) so I don't have to keep track of $index myself.
> First off, with that syntax you want to be doing a "foreach," not "for."

You spell potatoe, I spell potato.  :-)  They both do the same thing in
this context.  Foreach is clearer, but for is quicker to type...

>  I don't think there is a special variable a la $_ for loop iteration
> counting. 

Unfortunately there isn't.  The reason is that when traversing a list with
the foreach loop, I think perl traverses it more like a linked list than
an actual array, so it never really knows what number in the chain it is,
only if it's at the begining, middle, or end.

> I think what would work for you is:
>   $index = @list;
> at the loop exit, which will set $index equal to the number of elements
> in @list.  E.g.,
>   my $index;
>   my $element;
>   @list = ("Larry", "Moe", "Curly");
>   foreach $element (@list) {
>     ... # process $element
>   }
>   $index = @list;  # $index now equals 3

This works only if you want the count at the end.  The way that was
originally proposed is the best way to do it, at least that I am aware

 _ _ _
 Bobby Kleemann <rkleeman at>


The posting address is: san-diego-pm-list at

List requests should be sent to: majordomo at

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at> with the following
command in the body of your email message:

    unsubscribe san-diego-pm-list

If you ever need to get in contact with the owner of the list,
(if you have trouble unsubscribing, or have questions about the
list itself) send email to <owner-san-diego-pm-list at> .
This is the general rule for most mailing lists when you need
to contact a human.

More information about the San-Diego-pm mailing list