Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: matching a regular expression

by Jasper (Chaplain)
on May 18, 2006 at 14:16 UTC ( #550240=note: print w/ replies, xml ) Need Help??


in reply to matching a regular expression

How about:

"hsbn" =~ /^$state/ || "admin" =~ /^$state/

I think that should work. Unless I'm not seeing something :)


Comment on Re: matching a regular expression
Download Code
Re^2: matching a regular expression
by sgifford (Prior) on May 18, 2006 at 15:50 UTC
    That's a good trick, as long as the user's input is trusted; otherwise it may cause arbitrary perl code to execute. If you filtered their input to only letters and numbers, it would be safe.

    Update:ikegami points out that this is only true if use re 'eval'; is on, and perlre(1) confirms this. \Q/\E should help with the possibility of creating a really slow regex, and reduce the chances of tickling a bug in Perl's regex engion that turns out to be exploitable.

      Well said: just one more reason to use index instead of a regexp that fundamentally "emulates" index.

        Unless you wanted case insensitive indexing, which I'm not sure exists.

        You're being far too dismissive of the usefulness of a regex, I think.
        I know this is pedantic, but index() doesn't stop looking after it fails to find the target at position 0 of the string. The regex does. The regex fails very fast. Add a \Q...\E and an /i modifier, and you have a perfectly reasonable solution. And, as my solution above showed, you can get more bang for your buck.

        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      Ah, yes, I see what you mean. Easily solved with a \Q, though.

      That's not true. Without use re 'eval', it won't execute Perl code.

      my $input = '(?{ print("Hello World!\\n") })'; print(qq{Without "use re 'eval';":\n}); eval { '' =~ /$input/; }; warn($@) if $@; print("\n"); print(qq{With "use re 'eval';":\n}); eval { use re 'eval'; '' =~ /$input/; }; warn("Died: $@") if $@;

      outputs

      Without "use re 'eval';": Died: Eval-group not allowed at runtime, use re 'eval' in regex m/(?{ +print("Hello World!\n") })/. With "use re 'eval';": Hello World!

      On the other hand, some regexps take forever to execute. Some might even crash perl.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://550240]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (14)
As of 2014-12-29 13:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (188 votes), past polls