If during the iteration you need an index / key, then you need to use each :
@x = qw/ 1 2 3 abc /; while( my( $idx, $value ) = each @x ){ print "$idx -- $value\n" } 0 -- 1 1 -- 2 2 -- 3 3 -- a 4 -- b 5 -- c
There is also sugar: starting with perl-5.18 each sets $_ to the current index / key. Therefore, you can write like this:
@x = qw/ 1 2 3 abc /; while( each @x ){ print "$_ -- $x[$_]\n" } 0 -- 1 1 -- 2 2 -- 3 3 -- a 4 -- b 5 -- c
And if you just need to print out the indices, then you have 2 more options:
print while each @x; # 012345 print keys @x; # 012345
Doc: each and keys
If it is necessary through for , then there are no other options, except as add. variable:
print 0+$i, " -- $x[$i++]\n" for @x
say "[$_] $array[$_]" for ( 0 .. $#array )Or another task from a strange teacher? Well, thenmy $i = 0; for( @array ) { printf "[%u] %s\n", $i++, $_ };my $i = 0; for( @array ) { printf "[%u] %s\n", $i++, $_ };But why such complications and disregard for the KISS principle is not clear. - PinkTux