数组 – 如何在Perl中不使用循环来过滤数组?
发布时间:2020-12-15 21:21:28 所属栏目:大数据 来源:网络整理
导读:在这里,我试图仅过滤没有子字符串世界的元素,并将结果存储回同一个数组。在Perl中这样做的正确方法是什么? $ cat test.pluse strict;use warnings;my @arr = ('hello 1','hello 2','hello 3','world1','hello 4','world2');print "@arrn";@arr =~ v/worl
在这里,我试图仅过滤没有子字符串世界的元素,并将结果存储回同一个数组。在Perl中这样做的正确方法是什么?
$ cat test.pl use strict; use warnings; my @arr = ('hello 1','hello 2','hello 3','world1','hello 4','world2'); print "@arrn"; @arr =~ v/world/; print "@arrn"; $ 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 "@arrn"; foreach(@arr) { unless ($_ =~ /world/i) { push (@arrf,$_); } } print "@arrfn"; $ 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 "@arrn"; @narr = grep(!/world/,@arr); print "@narrn"; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |