Perl is equivalent to Php foreach loop

I am looking for the Perl equivalent for the following PHP code: -

foreach($array as $key => $value){ ... } 

I know I can make a foreach loop like this: -

 foreach my $array_value (@array){ .. } 

Which will allow me to do something with array values, but I would also like to use keys.

I know there is a Perl hash that allows you to set key-value pairs, but I just need the index number, which automatically gives you an array.

+6
source share
3 answers

If you use Perl 5.12.0 or higher, you can use each for arrays:

 my @array = 100 .. 103; while (my ($key, $value) = each @array) { print "$key\t$value\n"; } 

Conclusion:

 0 100 1 101 2 102 3 103 

perldoc each

+14
source

Try:

 my @array=(4,5,2,1); foreach $key (keys @array) { print $key." -> ".$array[$key]."\n"; } 

Works for hashes and arrays. In the case of arrays, the $ key contains an index.

+7
source

I think the closest Perl looks something like this:

 foreach my $key (0 .. $#array) { my $value = $array[$key]; # Now $key and $value contains the same as they would in the PHP example } 

Starting with Perl 5.12.0, you can use the keys function for arrays as well as for hashes. It may be a little more readable.

 use 5.012; foreach my $key (keys @array) { my $value = $array[$key]; # Now $key and $value contains the same as they would in the PHP example } 
+6
source

Source: https://habr.com/ru/post/915896/


All Articles