代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

在Perl中,如何在不使用循环的情况下过滤数组?

  •  27
  • Aakash Goel  · 技术社区  · 15 年前

    这里我只过滤没有子字符串的元素 world

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

    我想知道是否有一种方法可以不用循环(使用一些简单的过滤)。

    4 回复  |  直到 15 年前
        1
  •  37
  •   Ruel    15 年前

    那就是 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";
    
        2
  •  11
  •   Greg Bacon    15 年前

    使用 grep :

    sub remove_worlds { grep !/world/, @_ }
    

    例如:

    @arrf = remove_worlds @arr;
    

    使用 格雷普 map :

    sub remove_worlds { map /world/ ? () : $_, @_ }
    

    这里有点脏,但是 地图 提供一个钩子,以防在丢弃筛选的元素之前对其进行处理。

        3
  •  10
  •   Andy Lester    15 年前

    grep

    @no_world_for_tomorrow = grep { !/world/ } @feathers;
    

    关于细节, perldoc -f grep .

        4
  •  5
  •   codaddict    15 年前

    你可以使用 grep

    @arrf =  grep(!/world/, @arr);
    

    表达 !/world/ 对数组的每个元素求值 @arr 返回表达式计算为true的元素列表。

    表达 /world/ 搜索单词 world 是真的,它就在眼前。以及表达方式 如果字符串为 世界