[Mimedefang] Code fragment works only sometimes

Michael Sims michaels at crye-leike.com
Tue Jul 15 14:30:02 EDT 2003

Quoting "Kevin A. McGrail" <kmcgrail at peregrinehw.com>:

> I must admit, I am confused why would you need to run a regexp variable
> through quotemeta?  Has $line already been run through quotemeta and you
> won't get a match otherwise?  Some sort of safety test I'm not familiar
> with?

Although the original poster didn't specify what his $blk contains, I'm assuming
it is literal strings that he wants to match on, since he was using rindex()
instead of a regex match.  If these literal strings contain regex
metacharacters, they need to be quoted for a proper match.

Take this (admittedly contrived) example.  Say you want to match an email where
the headers (say, a Message ID) contain the literal string
"abcd+ef at example.com".  So you put that in your BLK file, and the line ends up
in the $blk variable.  If you do this:

if ($line =~ /$blk/i)

it is the equivalent of this:

if ($line =~ /abcd+ef\@example.com/i) 

This is no good, because perl will interpret the "+" as a modifier which says
that the "d" must occur one or more times, rather than seeing it as a literal
"+".  What we really want to do is this:

if ($line =~ /abcd\+ef\@example\.com/)

Which says to not treat the "+" and "." as metacharacters, but as literals.  To
acheive this programmatically, it's best to use quotemeta before inserting a
variable into a regex.

The exception to this is when you know that your variable contains a regex
pattern instead of a literal string to match, in which case running it through
quotemeta would be the wrong thing to do.


Michael Sims
Project Analyst - Information Technology
Crye-Leike Realtors
Office: (901)758-5648  Pager: (901)769-3722

More information about the MIMEDefang mailing list