I am matching the contents of 2 arrays like this:
foreach $headerLine(@headerLines)
{
if (grep { $headerLine =~ /$_/} @filterLines)
{
#do something
}
}
I need an exact match here, but ^$_$
does not work. How do I go about it?
You don't need a regex if you want an exact match.
if (grep { $headerLine eq $_ } @filterLines)
{
#do something
}
Your original problem was likely that $_
had special regex characters, and these are treated as regex syntax rather than matching those literal characters. For example, if $_
was ...
it would match any three characters rather than the exact string ...
. This also might result in an error if the variable didn't contain valid regex syntax (eg $_ = '('
).
You can get around this with the \\Q...\\E
quote literal construct:
if (grep { $headerLine =~ /^\Q$_\E$/} @filterLines)
{
#do something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.