Search code examples
arraysregexperl

How can I filter an array without using a loop in 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).


Solution

  • 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";