That is a much simpler approach, testing for what you won't accept.

In most cases, that's not true. The usual rule of thumb is to test for what you will accept, and it's a good one for several reasons...

It's usually less error prone. Not in a simple case like the OP's where perl provides both \w and the negated class \W, but in cases where you want to accept a more complex class like [\w.~%^+=-] negating the class isn't so easy.

Adding something to the class of what you will accept becomes difficult when you are trying to do it backward. For example, what if the OP wants to add a dash to the characters he will accept. You can't just add something to \W, you have to manually change it to a negated class like [^\w-]. And all the while, your code gets harder to read. It goes from "fail if I match a non-word character" to "fail if I match a character that is not a word character or a dash." Trying to turn that into a positive, the way we usually like to think, makes that "succeed if I do not match a character that is not a word character or a dash" and that requires a mental flip with a half-twist.

Another good reason to specify what you will accept rather than what you won't: untainting tainted data. In order to untaint, you need to capture what you want to keep anyway.

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Re: Code Cleanup challenge! by sauoq
in thread Code Cleanup challenge! 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.