数组 – 如何在Perl中不使用循环来过滤数组?

前端之家收集整理的这篇文章主要介绍了数组 – 如何在Perl中不使用循环来过滤数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这里,我试图仅过滤没有子字符串世界的元素,并将结果存储回同一个数组。在Perl中这样做的正确方法是什么?
  1. $ cat test.pl
  2. use strict;
  3. use warnings;
  4.  
  5. my @arr = ('hello 1','hello 2','hello 3','world1','hello 4','world2');
  6.  
  7. print "@arr\n";
  8. @arr =~ v/world/;
  9. print "@arr\n";
  10.  
  11. $ perl test.pl
  12. Applying pattern match (m//) to @array will act on scalar(@array) at
  13. test.pl line 7.
  14. Applying pattern match (m//) to @array will act on scalar(@array) at
  15. test.pl line 7.
  16. Syntax error at test.pl line 7,near "/;"
  17. Execution of test.pl aborted due to compilation errors.
  18. $

我想把数组作为参数传递给一个子程序。

我知道一种方式将是这样的东西

  1. $ cat test.pl
  2. use strict;
  3. use warnings;
  4.  
  5. my @arr = ('hello 1','world2');
  6. my @arrf;
  7.  
  8. print "@arr\n";
  9.  
  10. foreach(@arr) {
  11. unless ($_ =~ /world/i) {
  12. push (@arrf,$_);
  13. }
  14. }
  15. print "@arrf\n";
  16.  
  17. $ perl test.pl
  18. hello 1 hello 2 hello 3 world1 hello 4 world2
  19. hello 1 hello 2 hello 3 hello 4
  20. $

我想知道是否有办法没有循环(使用一些简单的过滤)。

解决方法

那将是grep():
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. my @arr = ('hello 1','world2');
  7. my @narr = ( );
  8.  
  9. print "@arr\n";
  10. @narr = grep(!/world/,@arr);
  11. print "@narr\n";

猜你在找的Perl相关文章