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?? |
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:
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.
In Section
Seekers of Perl Wisdom
|
|