global special variable for array index?

Bruce Timberlake brucet at onebox.com
Thu Apr 20 19:03:04 CDT 2000


~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...

But "for" syntax is (according to The Camel, anyway):

  for ( initial_exp; test_exp; re-init_exp ) {
    statement_1;
    statement_2;
    statement_3;
  }

The code listed more closely matches the "default" foreach syntax, so
that's what I guessed was really meant... :)

I guess with a "for" loop you could do something like:

  my($i, $index);
  @list = (qw(Larry Moe Curly));
  $index = @list;

first, and then set up your loop as

  for ($i = 1; $i <= $index; $i++ ) {
    $element = $list[$i];
    ... # process $element
  }

but foreach is just so much cleaner...

> 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
> of.  

What was originally proposed did not specify whether the iteration count
was or was not being used inside the loop.  As there was no reference
to $index other than the increment, I guessed it wasn't important within
the loop itself.  You are correct: if you need access to the iteration
count while inside the loop, then yes, the original idea is the only
one which works.

Bruce

__________________________________________________
FREE voicemail, email, and fax...all in one place.
Sign Up Now! http://www.onebox.com

~sdpm~

The posting address is: san-diego-pm-list at hfb.pm.org

List requests should be sent to: majordomo at hfb.pm.org

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at happyfunball.pm.org> 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 happyfunball.pm.org> .
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