我如何过滤不使用Perl中的一个循环数组? [英] How can I filter an array without using a loop in Perl?

查看:168
本文介绍了我如何过滤不使用Perl中的一个循环数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我想筛选只是没有一个子全球,并将结果保存回相同的数组中的元素。什么是Perl中做到这一点的正确方法?

Here I am trying to filter only the elements that do not have a substring world and store the results back to the same array. What is the correct way to do this in 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.
$

我要数组作为参数传递给子例程。

I want to pass the array as an argument to a subroutine.

我知道有一个办法是这样的

I know one way would be to something like this

$ 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
$

我想知道是否有办法做到这一点不循环(使用一些简单的过滤)。

I want to know if there is a way to do it without the loop (using some simple filtering).

推荐答案

这是的grep()

#!/usr/bin/perl

use strict;
use warnings;

my @arr = ('hello 1', 'hello 2', 'hello 3', 'world1', 'hello 4', 'world2');
my @narr = ( );

print "@arr\n";
@narr = grep(!/world/, @arr);
print "@narr\n";

这篇关于我如何过滤不使用Perl中的一个循环数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆