How can I filter an array without using a loop in Perl?

前端 未结 4 1469
一整个雨季
一整个雨季 2020-12-29 03:34

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

相关标签:
4条回答
  • 2020-12-29 03:50

    Use grep:

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

    For example:

    @arrf = remove_worlds @arr;
    

    Using grep is the most natural fit for your particular problem, but for completeness, you can also do it with map:

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

    It's a bit klunky here, but map gives you a hook in case you want to process the filtered elements before discarding them.

    0 讨论(0)
  • 2020-12-29 03:54

    Use grep

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

    For details, perldoc -f grep.

    0 讨论(0)
  • 2020-12-29 04:02

    You can use the grep function as:

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

    The expression !/world/ is evaluated for each element of the array @arr and a list of elements which which the expression evaluated to be true is returned.

    The expression /world/ searches for the word world and is true it's present. And the expression !/world/ is true if the string world is absent.

    0 讨论(0)
  • 2020-12-29 04:04

    That would be 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";
    
    0 讨论(0)
提交回复
热议问题