Jaron787 Jaron787 - 10 months ago 55
Perl Question

Perl grep exact value in array

I have the following values in an array:



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?


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