[perl] Automatically get loop index in foreach loop in Perl

If I have the following array in Perl:

@x = qw(a b c);

and I iterate over it with foreach, then $_ will refer to the current element in the array:

foreach (@x) {

will print:


Is there a similar way to get the index of the current element, without manually updating a counter? Something such as:

foreach (@x) {
    print $index;

where $index is updated like $_ to yield the output:


This question is related to perl foreach

The answer is

Like codehead said, you'd have to iterate over the array indices instead of its elements. I prefer this variant over the C-style for loop:

for my $i (0 .. $#x) {
    print "$i: $x[$i]\n";

Similar questions with perl tag:

Similar questions with foreach tag: