【发布时间】:2011-04-26 23:29:11
【问题描述】:
这里我试图只过滤没有子字符串world 的元素并将结果存储回同一个数组。在 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', 'hello 2', 'hello 3', 'world1', 'hello 4', '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
$
我想知道是否有办法不使用循环(使用一些简单的过滤)。
【问题讨论】: