Want to perform an exact match with Perl's grep function?
Perl's grep function is incredibly powerful. However, at first glance it can seem as if Regular Expressions are going to trip you up. For example, if you want to perform an exact match with data that might contain Regualr Expression special characters. For example, this looks like it might be a problem...
my @elements=("apple", "apple.", "apple1", "apple2", "banana");
my @results=grep(/apple/,@elements);5
Here, @results will contain "apple", "apple.", "apple1" and "apple2". This can or course be avoided as follows:
my @results=grep(/^apple$/,@elements);
Which will only put "apple" into the results. But what if the search term contains metacharacters (like . * ? etc)? For this you need a non-regular expression version of grep. Here's an example:
my @results=grep( { "$_&" eq "apple." } @elements);
Here, @results will only contain "apple.", because it's the only thing that matches exactly. The check is a simple string "eq" rather than a regular expression, so metacharacters aren't used. Rememeber, this won't work:
my @results=grep(/^apple.$/, @elements);
...becuase the "." will match any single character. You'll end up with "apple.", "apple1" and "apple2" in @results.
ALSO SEE:
Comments
if you are interested only in "apple."
What about the following...
my @results=grep(/^apple\.$/, @elements);
seems simpler than
my @results=grep( { "$_" eq "apple." } @elements);
Yep, for sure. Indeed, you can use the quotemeta() function to do just that. However, in more complex scenarios, an exact match can be useful.
how do i get all occurrences that do not match "john"? i know on the command line you can do grep -vbut how about perl?
Roumen Semov
Here you go:
grep !/john/, @array1;
Roumen Semov
Thank you for this helpful tip.
Mauricio
Perl grep is very powerful. I didn't know about Perl Grep until recently and always was using Linux grep to do stuff. Thanks for the tip. Also found this interesting tutorial on perl grep: http://programmingbulls.com/perl-grep
my @results=grep(/^apple\.$/, @elements);
This will match any regexp in input, like ? or *, it's dangerous
my @results=grep( { "$_" eq "apple." } @elements);
This one will match only the exact string
Try it..