简体   繁体   English

如何将多个数组传递给Perl中的'foreach'循环?

[英]How do I pass multiple arrays to a 'foreach' loop in Perl?

I want to write items from two arrays into a file, like 我想把两个数组中的项目写入文件,比如

 @a = ('1', '2', '3')
 @b = ('0.1', '0.2', '0.3')

I want my output like this: 我希望我的输出像这样:

1 0.1
2 0.2
3 0.3

in the file. 在文件中。

I tried using two foreach loops, which is obviously wrong, 我尝试使用两个foreach循环,这显然是错误的,

 foreach my $a (@a) {
    foreach my $b (@b) {
        print FP "$a $b \n";
    }
 }

This is wrong. 这是错的。 How do I pass multiple arrays to a foreach loop in Perl? 如何将多个数组传递给Perl中的foreach循环?

If you want to output all elements of @a and @b in parallel, you can loop through all indices of one of them (arrays are of same size so it doesn't matter which), and use it to access actual elements ( $a[$i] and $b[$i] ) 如果要并行输出@a@b所有元素,可以循环遍历其中一个元素的所有索引(数组大小相同,因此无关紧要),并使用它来访问实际元素( $a[$i]$b[$i]

foreach my $i (0 .. $#a) {
  print "$a[$i] $b[$i] \n";
}
@a=('1','2','3');
@b=('0.1','0.2','0.3');

print "$a[$_] $b[$_] \n" for (0 .. $#a);

Of course this assumes @a and @b are of equal lengths. 当然这假设@a和@b长度相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM