Sudhir Mishra Sudhir Mishra - 10 months ago 46
Perl Question

finding matched string with grep does not return the matched value

I am using the below code to get the matched value from grep function in perl , but it always returns a value of 1 instead of returning the matched value.

use strict;
use warnings;

my @capture = "err=\"some value\"";

if(my @matched_string = (grep(/\berr\b/, @capture) || grep(/\bwarn\b/, @capture))){
print "@matched_string";

How can i get the matched value.


The OR (||) imposes the scalar context on the first (left) grep call. So it returns the number of times it matched, which is then evaluated for truth. If it matched anything that number evaluates as true, so that number is returned by ||. Otherwise you get the other list, or an empty list if that one doesn't have a match either.

I take it that you want to get all lines with err from @capture or, if absent altogether, then all with warn. For this you have the make the full pass for err first, then look for warn. A simple way

my @matched_string = grep { /\berr\b/ } @capture;
@matched_string = grep { /\bwarn\b/ } @capture  if not @matched_string;

But if you simply want all strings in @capture with either err or warn words in them, then

my @matched_string = grep { /\b(?:err|warn)\b/ } @capture;

Please clarify the purpose if the above guesses aren't right.