in reply to hex-only regex

Your first regex might be better if you force it to match the whole string:

if ($hash =~ /^[0-9a-f]{32}$/i) { return(1); }

This way, it doesn't match a good hash that also has some other junk with it. My guess is that you may be checking the string's length separately, in which case this isn't really necessary, but it might be nice to consolidate those checks.

I don't see anything wrong with your other pattern.

Replies are listed 'Best First'.
Re^2: hex-only regex
by merlyn (Sage) on Jan 17, 2007 at 16:44 UTC
    Don't fall for the "dollar mistake" here. Remember that $ doesn't match end of string: it matches "end of string or just before a newline at end of string".

    This means that you could have "123423453456456756786789789a89ab\n" in your string, and it'd still match. While this may not make any difference for your application, in some cases this could be a missed crucial check for a security validation, allowing a messy character where it doesn't belong (such as in a filename).

    Beware the dollar. Use \z instead: /^[0-9a-f]{32}\z/i.

      Fascinating. I need to read perlre more often.

      Does m/regular$/s also work reliably or is \z the only safe way to do it? Until today, I've always used the former to change the meaning of $. UPDATE: Nope. It's not reliable at all. In fact, I'd go so far as to say it doesn't even work.

      -Paul

        /s makes dot match newline. The description "treat string as a single line" is, IMO, completely unhelpful.

        Caution: Contents may have been coded under pressure.