http://www.perlmonks.org?node_id=11157583


in reply to Invert grep match with qr// variable

It is possible to put the inversion in the regexp, but I don't recommend it: it will in almost all cases be much less efficient.

Here's how it works: $string =~ /$re/ matches if $re matches at any point in the string; $string =~ /(?!$re)/ matches if there is any point in the string that does not match $re; $string =~ /^(?!.*$re)/s therefore matches only if there is no point in the string that matches $re, and is therefore the inverse.

Inverting outside the pattern just requires one of a couple of ways to ensure the interpreter knows it should do a pattern match:

grep !/$re/, @array; # use // round $re to treat as a pattern match grep $_ !~ $re, @array; # use a negating match

Note that if $re is a precompiled regexp, perl won't need to recompile it just because you put // round it.

Hugo