Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Detecting if a string is a regular expression

by LanX (Canon)
on Jan 10, 2013 at 19:58 UTC ( #1012731=note: print w/ replies, xml ) Need Help??


in reply to Detecting if a string is a regular expression

> Is there some quick and dirty way to detect is a string is a pure string, or if it is a regular expression.

no, IMHO any $string can be used as a valid regex like in m/$string/ w/o syntax error.

but if you need a regex datatype to distinguish $scalars use qr// to generate them.

DB<106> $s='abc' => "abc" DB<107> $r=qr/abc/ => qr/abc/ DB<108> ref $r eq 'Regexp' => 1 DB<109> ref $s eq 'Regexp' => "" DB<110> 'xabcx'=~m/$r/ => 1 DB<111> 'xabcx'=~m/$s/ => 1

Cheers Rolf


Comment on Re: Detecting if a string is a regular expression
Select or Download Code
Re^2: Detecting if a string is a regular expression
by AnomalousMonk (Abbot) on Jan 10, 2013 at 23:40 UTC
    ... any $string can be used as a valid regex like in m/$string/ ...

    ... and you don't even need the  m// or  qr// incantation. The  =~ binding operator can do the trick:

    >perl -wMstrict -le "my $s = 'abc'; ;; print 'match' if 'xabcx' =~ $s; print 'match' if 'xabcx' =~ 'abc'; " match match
      yeah I noticed, but normally I prefer the more obvious syntax. (the m is superfluous too =)

      Cheers Rolf

      PS: I know someone will show us now benchmarks demonstrating that at least 3 and half processor cycles are waisted this way ... ;)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2014-12-20 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (95 votes), past polls