There is an array:

my @a = qw/qaz wsx edc/; 

It is necessary to display all elements with indexes.

 for(@a){ print $_ "индекс массива" } qaz0 wsx1 edc2 

options with 0..$#a or scalar @a - 1 do not fit, is there another way to print them? but with the condition that the code should start like this: for(@a){ or for my $a(@a){

  • one
    and just get an additional variable? - KoVadim
  • maybe special? "$.", "$ - [0]" and so on, there is a lot of them, you can't remember everyone - that's why I ask - usr13
  • from what I know, there is no such variable. All variables can be seen in perlvar - KoVadim
  • extra, so, like ?: my $ i = 0; for (@a) {print "$ _ $ i"; $ i ++; } - usr13
  • one
    options ... not suitable - why would? say "[$_] $array[$_]" for ( 0 .. $#array ) Or another task from a strange teacher? Well, then my $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

1 answer 1

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