Perl相当于Php foreach循环

fbc*_*fbc 7 php perl foreach

我正在寻找一个相当于以下PHP代码的Perl: -

foreach($array as $key => $value){
...
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以像这样做一个foreach循环: -

foreach my $array_value (@array){
..
}
Run Code Online (Sandbox Code Playgroud)

这将使我能够使用数组值进行操作 - 但我也想使用这些键.

我知道有一个Perl哈希允许你设置键值对,但我只想要数组自动给你的索引号.

fle*_*esk 15

如果您使用的是Perl 5.12.0或更高版本,则可以each在数组上使用:

my @array = 100 .. 103;

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

输出:

0       100
1       101
2       102
3       103
Run Code Online (Sandbox Code Playgroud)

perldoc每个

  • 是的,懒惰的'while`比渴望的'foreach`更可取. (2认同)

int*_*000 7

尝试:

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

适用于哈希和数组.在Arrays的情况下,$ key保存索引.


Dav*_*oss 7

我猜最接近的Perl是这样的:

foreach my $key (0 .. $#array) {
  my $value = $array[$key];

  # Now $key and $value contains the same as they would in the PHP example
}
Run Code Online (Sandbox Code Playgroud)

从Perl 5.12.0开始,您可以keys在数组和散列上使用该函数.这可能更具可读性.

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
}
Run Code Online (Sandbox Code Playgroud)