in reply to Re: Code Cleanup challenge!
in thread Code Cleanup challenge!

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.";

Replies are listed 'Best First'.
Re^3: Code Cleanup challenge!
by Aristotle (Chancellor) on Aug 11, 2003 at 21:32 UTC
    In order to untaint, you need to capture what you want to keep anyway.

    For the sake of being argumentative, no, you don't have to. This is Perl though, you're free to shoot yourself in the foot. You could f.ex s/// everything you want to disallow, then capture /(.*)/s.

    But obviously, the untaint mechanism was chosen to encourage "allow what you will accept" logic.

    Makeshifts last the longest.

      For the sake of being argumentative

      I'll point out that you are still capturing what you want to keep and you are hoping that after your s/// you want to keep everything.

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