Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl equivalent to Php foreach loop

Tags:

foreach

php

perl

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.

like image 842
fbc Avatar asked May 16 '12 09:05

fbc


3 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

like image 103
flesk Avatar answered Sep 30 '22 20:09

flesk


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.

like image 41
int2000 Avatar answered Sep 30 '22 18:09

int2000


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
}
like image 42
Dave Cross Avatar answered Sep 30 '22 18:09

Dave Cross