I was a little surprised that in a recent thread no one seemed to flinch at code that was essentially the equivalent of $logged_in = $expect_pass=~/$FORM{pass}/i;.

If you happen to be wondering "Why is that bad?" - Because $FORM{pass} most likely comes from an HTML form (or at the very least could contain user input), and its contents will be interpolated into and interpreted as a regular expression, leaving the user free to input ".*", which of course matches anything, and so the user is always logged in!

One solution is to use /\Q$FORM{pass}\E/, which causes characters that would normally be special in a regular expression to be escaped - see quotemeta. In addition, the regex should probably be anchored, to prevent partial matches: /^\Q$FORM{pass}\E$/. Of course, in this example the much easier solution is to just use $expect_pass eq $FORM{pass} instead of a regex!

I feel like \Q...\E is forgotten too often when interpolating variables into regexes, and it seems to be often overlooked here on PerlMonks when people post code like the above. In fact, I see it forgotten often enough that I think instead \Q...\E should be everyone's default thought when interpolating variables into regular expressions, only to be left off when one has a good reason to (like dynamically building regexes - but of course doing that with unchecked user input is dangerous!).

So please, mind the meta(characters) and remember \Q...\E!


In reply to Mind the meta! by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.