in reply to Abbreviation regex?

You could just reverse your regex with the match variable:

if ( "abbreviation" =~ m/^$str/ ) { #...

Still a regex solution, just not a refactoring of that regex solution.

Replies are listed 'Best First'.
Re^2: Abbreviation regex?
by Tanktalus (Canon) on Jan 16, 2006 at 17:55 UTC

    ++ I like the thinking outside the box. That said, you can only do that if $str comes from a trusted source. If, for example, you get it from user input, try this as input:

    abbr(?{system qw(format c:)})ev
    Of course, that's only really a problem if you have enabled use re 'eval'; - but if you already need that for other purposes, you'll need to be very careful.

    In fact, your "outside the box" is almost exactly described in the documentation for the (?{ code }) construct in perlre where it goes into a bit more detail and talks about ways to mitigate it.

      The injection attack (and the bug preventing the use of special characters) is fixed by simply adding \Q!
      if ( "abbreviation" =~ m/^\Q$str/ ) { #...

      Naturally... there are a number of downsides to this solution. The most obvious to me is overhead. If we are scanning a file, we need to recompile a trivial regex for each work. The substr solution above is much faster and safe from exploit.

      I've seen it somewhere before. I don't know where, though. I think that it resides in the place for things that are idiomatic but not useful enough to be idioms.