develooper Front page | perl.beginners | Postings from February 2002

Re: iteration default variable

Thread Previous
From:
John W. Krahn
Date:
February 27, 2002 12:56
Subject:
Re: iteration default variable
Message ID:
3C7D47D2.11AE026A@acm.org
Michael Kavanagh wrote:
> 
> Hi there,

Hello,

> This is probably a simple one...
> 
> in a loop like this:
> 
> for (@answer) {
>         #do something ...
> }
> 
> I understand that for each iteration of the loop, $_ contains the value of
> $answer[current iteration].
> But is there a default variable I can use to get the current index value?


No, Perl doesn't provide a variable for this but it is fairly easy to
do.

for my $iterator ( 0 .. $#answer ) {
    #do something with $answer[$iterator]
}

Or you can use the C style of for loop.

for ( my $iterator = 0; $iterator < @answer; ++$iterator ) {
    #do something with $answer[$iterator]
}



John
-- 
use Perl;
program
fulfillment

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About