monucool
monucool

Reputation: 432

mimic linux grep -w in perl grep

Grep in perl gives me all the matched lines with the regular expression.

For ex-

{
    my @FAMILY_MAP= ("A2LVLX","LVLX","O2LVLX");
    my $search="LVLX";
    my @match = grep (/ALVL/, @FAMILY_MAP);
    print @match;
 }

Here my expected output is LVLX but i get all the three elements in the array. Which is expected behaviour in the Linux terminal too(if grep LVLX is done on a file containing the three words). But i have to used grep -w "LVLX" in the terminal to get LVLX as the output. I need a way to replicate the same using perl grep. Any hints?

Upvotes: 0

Views: 248

Answers (2)

simbabque
simbabque

Reputation: 54381

If you want an exact match, you need to tell it. Your pattern /LVLX/ matches strings that contain the pattern, because you have not anchored it.

There are two ways to do this. Either you anchor your pattern like this

my @match = grep(/^ALVL$/, @FAMILY_MAP);

or you use the block form of grep and do an equality check, which is faster in older Perls (very new Perls have this optimized, but I don't remember in which version that was introduced)

my @match = grep { $_ eq 'ALVL' } @FAMILY_MAP;

Both will give you the same output.

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69314

grep -w matches the string only when it appears as a whole word. For that, you need to use the word boundary (\b) escape sequence in your regex.

my @family_map = ("A2LVLX","LVLX","O2LVLX");
my $search = 'LVLX';
my @match = grep (/\b$search\b/, @family_map);
print "@match";

Update: Alternatively, if you know the elements of your array will all be individual words, then just use eq.

my @match = grep( $_ eq $search, @family_map);

Upvotes: 6

Related Questions