hitman99
hitman99

Reputation: 63

Remove items from array in perl using logical OR

I have a one array . I want the array to be such that it does not have any values of $regex (in a logical OR way). I am using grep command in a negation way, but I don't think this is solving my problem. Any help is highly appreciated. Thanks

 #!/usr/bin/perl -w 

use Data::Dumper;

    my @array = ['hard_link is not present', 'dynamic variable', 'segfault'] ;

    my $regex = qr/create_hard_link|Failed to reassign|Global variable/ ;

    print Dumper(\@array) ;
    my @wanted_array = grep  {!$regex} @array ;
    print Dumper(\@wanted_array);

it gives me an output as

$VAR1 = [
          [
            'hard_link is not present',
            'dynamic variable',
            'segfault'
          ]
        ];
$VAR1 = [];

Upvotes: 2

Views: 127

Answers (2)

ikegami
ikegami

Reputation: 386706

Unlike the command line tool by the same name, grep doesn't take a regex pattern; it takes an expression that evaluate to a true value for the items to keep.

$regex has a true value —the compiled regex pattern doesn't stringify to 0 or the empty string— so !$regex is always false, so grep filters everything out. You want to perform a regex match, so you will need the regex match operator.

my @wanted_array = grep  { !/$regex/ } @array;

There is a second problem.

# An array that contains a single element: a reference to an anonymous array.
my @array = ['hard_link is not present', 'dynamic variable', 'segfault'];

should be

# An array that contains a three strings.
my @array = ('hard_link is not present', 'dynamic variable', 'segfault');

Upvotes: 4

melpomene
melpomene

Reputation: 85907

First off, don't use -w in scripts (unless you're a time traveler from before 2000).

Always start your Perl files with use strict; use warnings;.

The problem in your code is that you're using !$regex as the filter condition. $regex contains a regex object, which is a true value, so negating it returns false. This is why you end up with an empty array.

Fix: Actually do a regex match:

my @wanted_array = grep { !/$regex/ } @array;

(This uses the match operator m// (but the m is optional if you're using / as the delimiter).)


The other problem is that your @array only contains a single element, which is a reference (to another array).

You want

my @array = ('hard_link is not present', 'dynamic variable', 'segfault');

[ ... ] is a single scalar value.

Upvotes: 2

Related Questions