tags:

views:

155

answers:

4

Possible Duplicate:
automatically get loop index in foreach loop in perl

I'd like to iterate over an array, but I need to keep track of the index. This code doesn't list the indexes as I'd expect - how can I fix it?

$arr = [0,0,0,0];
foreach $i (0 .. scalar @$arr) { print $i; }
A: 

Actually it works. Just noticed that re.pl is hiding my output. Printing "$i\n" works of course.

viraptor
Don't post non-answers as answers. Either update the question or use comments. Also, what on earth is `re.pl`?
Sinan Ünür
It does not work -- at least not correctly -- because `scalar @$arr` is too large by 1. See the answer from eugene y for the correct approach.
FM
Well - it was an answer to my problem, but the problem was a non-problem ;)
viraptor
+7  A: 

To get a range of indexes for the array use 0 .. $#$arr.
scalar @$arr returns the number of elements in the array.

eugene y
+2  A: 

To add to eugene's answer: a little more standard way is

for( my $i = 0; $i <= $#$arr ; $i++)  { 
   ...
}
leonbloy
Whoa there! C-style `for` loops are rarely needed. Range operators are sufficient: `for my $i (0 .. $#arr) {...`
Zaid
Also, because `$arr` is an array ref in this case, you need `$#$arr`, not `$#arr`.
FM
@FM: you're right, corrected.
leonbloy
+6  A: 

From Perl 5.12 you can use each on an array:

use 5.012;
use warnings;

my @array = 'a' .. 'h';

while (my ($i, $val) = each @array) {
    say "$i => $val";
}

For some more info see blog post: each @array in Perl 5.12

/I3az/

draegtun