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.
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
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With