Automatically get loop index in foreach loop in Perl

perl for loop
perl for loop array
perl foreach
perl foreach hash
perl foreach my
perl foreach next
perl for vs foreach
perl inline foreach

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:


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";

Perl for loop explained with examples, for(INITIALIZE, TEST, STEP) {} C-style for loops in perl and the foreach loop for iterating over lists. In this part of the Perl Tutorial we are going to talk about the for loop in Perl. for (my $i=0; $i <= 9; $i++) {; print "$i\n";; } STEP is another set of action usually used to increment or decrement some kind of an index. This too  Uncategories Tutorial :automatically get loop index in foreach loop in perl. Tutorial :automatically get loop index in foreach loop in perl Unknown 13:03. Unknown.

In Perl prior to 5.10, you can say


use strict;
use warnings;

my @a = qw/a b c d e/;

my $index;
for my $elem (@a) {
    print "At index ", $index++, ", I saw $elem\n";


for my $index (0 .. $#a) {
    print "At index $index I saw $a[$elem]\n";

In Perl 5.10, you use state to declare a variable that never gets reinitialized (unlike ones created with my). This lets you keep the $index variable in a smaller scope, but it can lead to bugs (if you enter the loop a second time it will still have the last value):


use 5.010;
use strict;
use warnings;

my @a = qw/a b c d e/;

for my $elem (@a) {
    state $index;
    say "At index ", $index++, ", I saw $elem";

In Perl 5.12 you can say


use 5.012; # This enables strict
use warnings;

my @a = qw/a b c d e/;

while (my ($index, $elem) = each @a) {
    say "At index $index I saw $elem";

But be warned: you there are restrictions to what you are allowed to do with @a while iterating over it with each.

It won't help you now, but in Perl 6 you will be able to say


my @a = <a b c d e>;
for @a Z 0 .. Inf -> $elem, $index {
    say "at index $index, I saw $elem"

The Z operator zips the two lists together (i.e. it takes one element from the first list, then one element from the second, then one element from the first, and so on). The second list is a lazy list that contains every integer from 0 to infinity (at least theoretically). The -> $elem, $index says that we are taking two values at a time from the result of the zip. The rest should look normal to you (unless you are not familiar with the say function from 5.10 yet).

Index of Items in Array using foreach loop, my @SampleArray = ("one","two","three" ); my $Arrayindex = 0; foreach my $​ArrayItem ( @SampleArray ){ print $ArrayItem , ' is at location '  Perl foreach loops. Sep 23, 2018 by brian d foy. A foreach loop runs a block of code for each element of a list. No big whoop, “perl foreach” continues to be one of the most popular on Google searches for the language.

perldoc perlvar does not seem to suggest any such variable.

Doing Something with Every Element in a List, foreach $var (sort keys %ENV) { print "$var=$ENV{$var}\n"; } The variable set to each value in the list is called a loop variable or iterator variable. foreach 's iterator variable ( $_ in this case) is automatically preserved during the loop. than the equivalent code using a three-part for loop and explicit indexing would be. The loops in Perl are : for loop; foreach loop; while loop; do…. while loop; until loop; Nested loops; for Loop “for” loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.

Not with foreach.

If you definitely need the element cardinality in the array, use a 'for' iterator:

for ($i=0; $i<@x; ++$i) {
  print "Element at index $i is " , $x[$i] , "\n";

while loops that have an index - DEV Community ‍ ‍ , Perl5 got this syntax that allow to use a while loop without having to automatically get loop index in foreach loop in perl on StackOverflow  The foreach loop iterates over a list value and sets the control variable (var) to be each element of the list in turn −. Syntax. The syntax of a foreach loop in Perl programming language is −

It can be done with a while loop (foreach doesn't support this):

my @arr = (1111, 2222, 3333);

while (my ($index, $element) = each(@arr))
   # You may need to "use feature 'say';"
   say "Index: $index, Element: $element";


Index: 0, Element: 1111
Index: 1, Element: 2222
Index: 2, Element: 3333

Perl version: 5.14.4

Perl foreach loops, A foreach loop runs a block of code for each element of a list. sub numbers{ keys %some_hash } foreach ( numbers() ) { print "\$_ is $_"; }. There are simpler ways than using the C-style for loop to iterate through every element of an array in Perl. If an array is passed to a for loop, it will iterate through every element of the array until it reaches the end.

Loop Statements (Programming Perl), All loop statements have an optional LABEL in their formal syntax. [3] That is, the fallout from the loop tends to occur automatically. That's because the foreach loop index variable is an implicit alias for each item in the list that you're looping  Is it possible to assign two variables the same data from an array in a Perl foreach loop? I am using Perl 5, I think I came across something in Perl 6. Something like this:

Iterate associative array using foreach loop in PHP, Both arrays can combine into a single array using a foreach loop. Array: Arrays in PHP How to get numeric index of associative array in PHP? How to check an  If you want the indexes instead of the elements.. well, Perl 6 added a grep-index method to handle that case, but in Perl 5 the easiest way is to change the target of grep. That is, instead of running it on the original array, run it on a list of indexes - just with a condition that references the original array.

Determine the first and last iteration in a foreach loop in PHP , Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration  When the continue statement jumps over code that changes our index variable, then the foreach loop goes on as normal but the index variable doesn't change. That creates mistakes and subtle bugs. # Option 2: Use a tuple to get the foreach loop's value and index. The second way to use an index variable with the foreach loop is with a tuple

  • This is not what you want if array index sequence is 2, 5, 8, 19 with gaps in sequence. I believe the question was something regarding index of current element.
  • I don't like the section on state, I think it would be better served with { my $index; ... }.
  • Great! Learned a lot.
  • AndrewKS: This certainly is not against the spirit of StackOverflow. If you had tried perldoc perlvar, you would know why. Only variables listed in perldoc perlvar exist. Such a variable, as I already stated, does not exist.
  • This is against the spirit of stackoverflow, because the spirit is to provide an answer that can answer a question in it's entirety, without external resources. Providing optional resources such as links or terminal commands to run for learning is a bonus, but not the spirit. The fact that you had to provide further information in a comment is proof that this answer is not enough on it's own.
  • This is basically the same as a link-only answer.
  • Perhaps expand your answer?
  • foreach and for are interchangeable synonyms. Some introductory material tries to use for to mean the C-style loop and foreach for the list iterator loop, but that use of terminology isn't going to be familiar to everyone.
  • foreach and for are /not/ interchangeable, as this instance shows.
  • Quoting from 'perldoc perlvar': The "foreach" keyword is actually a synonym for the "for" keyword, so you can use "foreach" for readability or "for" for brevity. endquote. So they are interchangeable. Try it.
  • The keywords are interchangeable -- but the loops themselves have different meanings. A "for" loop is a loop with an incrementing (or decrementing) variable, even if it's introduced with the foreach keyword. A "foreach" loop has an internal iterator, even if it's introduced with the for keyword. The OP wanted access to the iterator, so he wants a "for" loop, regardless of the keyword used.