Jaron787 Jaron787 - 7 months ago 32
Perl Question

Perl grep exact value in array

I have the following values in an array:

test1|value1
test2|value2
test3|value3


Code:

if (grep(/test1|value1/, @array)) {
print "Found";
}


I want the above code to only find exact match of "test1|value1" but it is returning found even if I run:

if (grep(/test3|value4/, @array)) {
print "Found";
}


What am I missing here?

Answer

Pipe | inside a regex is interpreted as or. It is documented in perlreref.

| Matches either the subexpression preceding or following it

So, If you want to match the words containing | you need to escape it inside regex. Now It is OK, but there is one problem it will also match test1|value1someothervalue or someothervaluetest1|value1 or someothervaluetest1|value1someothervalue etc.

But, you told you need exact match test1|value1. So, again from perlreref you need anchor ^ and dollar $ before and after your regex.

 ^       Matches at the beginning of the string (or line, if /m is used)
 $       Matches at the end of the string (or line, if /m is used)

So, It will become:

if (grep(/^test1\|value1$/, @array)) {
    print "Found\n";
  }
Comments