Home » Php » Perl equivalent to Php foreach loop

Perl equivalent to Php foreach loop

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am looking for a Perl equivalent to the following php code:-

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

I know I can do a foreach loop like so:-

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

Which will enable me to do things with the array values – but I would like to use the keys as well.

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

How to&Answers:

If you’re using Perl 5.12.0 or above you can use each on arrays:

my @array = 100 .. 103;

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

Output:

0       100
1       101
2       102
3       103

perldoc each

Answer:

Try:

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

Works for Hashes and Arrays.
In case of Arrays the $key holds the index.

Answer:

I guess the closest Perl is 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
}

Since Perl 5.12.0, you can use the keys function on arrays as well as hashes. That might 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
}