On Mon, 2006-09-18 at 08:28 -0700, Palit, Nilanjan wrote:
> That works too (& I have used it as well), but I guess what I'm really
> asking (hoping?) for is a Perl special variable, kinda like "$.", which
> Perl auto-magically initializes & increments ...

Perl6 will have a way of iterating over indices and values at the same
time.  I don't think anyone has back-ported it though.  The various
somewhat cumbersome ways to code it are your best approaches for now, if
you really need the index.

Note that you might be able to get away without the index, with a
suitable rearrangement of your code:

@newarray = map {complicated_function($_)} @array;

--kag

> -----Original Message-----
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] On
> Behalf Of Dan Boger
> Sent: Monday, September 18, 2006 10:39 AM
> To: boston-pm@mail.pm.org
> Subject: Re: [Boston.pm] Loop index in foreach?
> 
> On Mon, Sep 18, 2006 at 07:30:40AM -0700, Palit, Nilanjan wrote:
> > In a foreach loop, is there a way to find out the loop index number?
> > E.g.:
> > 
> > foreach (@myarray)
> > {
> > ...
> > push(@newarray[<??loopindex??>], <somevalue>);
> > ...
> > }
> > 
> > Currently, I have to resort to the following:
> > for (my $i= 0; $i <= $#myarray, $i++)
> > { ... push(@newarray[$i], <somevalue>); ...}
> > 
> >  ... which is more wordy -- I was wondering if there's a more
> > elegant/efficient (i.e. less code) to do this?
> 
> Not sure if I'd call this more elegant, but perhaps
> 
> my $index = 0;
> foreach (@myarray) {
>   ...
>   push(@newarray[$index], <somevalue>);
>   ...
> 
>   $index++;
> }
>   
> 

 
_______________________________________________
Boston-pm mailing list
Boston-pm@mail.pm.org
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to