在这里,我试图仅过滤没有子字符串世界的元素,并将结果存储回同一个数组。在Perl中这样做的正确方法是什么?
- $ cat test.pl
- use strict;
- use warnings;
- my @arr = ('hello 1','hello 2','hello 3','world1','hello 4','world2');
- print "@arr\n";
- @arr =~ v/world/;
- print "@arr\n";
- $ perl test.pl
- Applying pattern match (m//) to @array will act on scalar(@array) at
- test.pl line 7.
- Applying pattern match (m//) to @array will act on scalar(@array) at
- test.pl line 7.
- Syntax error at test.pl line 7,near "/;"
- Execution of test.pl aborted due to compilation errors.
- $
我想把数组作为参数传递给一个子程序。
我知道一种方式将是这样的东西
- $ cat test.pl
- use strict;
- use warnings;
- my @arr = ('hello 1','world2');
- my @arrf;
- print "@arr\n";
- foreach(@arr) {
- unless ($_ =~ /world/i) {
- push (@arrf,$_);
- }
- }
- print "@arrf\n";
- $ perl test.pl
- hello 1 hello 2 hello 3 world1 hello 4 world2
- hello 1 hello 2 hello 3 hello 4
- $
我想知道是否有办法没有循环(使用一些简单的过滤)。
解决方法
那将是grep():
- #!/usr/bin/perl
- use strict;
- use warnings;
- my @arr = ('hello 1','world2');
- my @narr = ( );
- print "@arr\n";
- @narr = grep(!/world/,@arr);
- print "@narr\n";