Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: qr expression defined as constant?

by ELISHEVA (Prior)
on Feb 16, 2011 at 07:21 UTC ( [id://888454]=note: print w/replies, xml ) Need Help??


in reply to qr expression defined as constant?

The reason constant isn't working for you is that what you get from use constant REGEX ==> is a subroutine: sub REGEX { qr/^(\d{4})-(\d{2})-(\d{2})/ }. In many cases this subroutine call gets reduced to a constant by the Perl optimizer. However, this happens after the parsing stage so constants declared with use constant can only be used in places where you could use a subroutine call.

Although you can use subroutine calls in the second half of a substitution regex (using the e or ee modifier), this is not so for the matching portion. Whether in substitutions or straight matching, the matching portion of a Perl regular expressions normally only allow the insertion of variables, not subroutine calls.

There is however an experimental feature (present since 5.8.8 but still in 5.12) that will allow expressions, including subroutine calls, to be evaluated in the matching portion: (??:{ expr }). Thus this works with a constant:

use constant REGEX => qr/^(\d{4})-(\d{2})-(\d{2})/; while (<>) { chomp; printf "$_: match=%s\n", ($_ =~ m{(??{REGEX})} ? 1 : 0); }

For more information on (??:{code}) check perlre.

As for using Readonly, it is a judgment call: the benefits of read-only-ness vs. performance/distribution issues. There are two versions of that module, a pure Perl implementation that uses tied variables and another that uses an XS module. The pure Perl implementation is significantly slower than a plain variable or a subroutine call. The XS version requires a compiler on your machine and any machine to which you distribute. For more discussion about trade-offs, see the the CONS section of the Readonly documentation.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-20 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found