Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: BEGIN block and failure to initialize constants

by tobyink (Abbot)
on Sep 17, 2012 at 22:10 UTC ( #994126=note: print w/ replies, xml ) Need Help??


in reply to BEGIN block and failure to initialize constants

The problem with your original version is that the use constant executes at compile time, but the regular expression executes at run time - i.e. after everything has been compiled - so it's setting the $CONF_PATH variable too late. To see the difference between compile time and run time, run this:

print "World\n"; BEGIN { print "Hello " };

And the use keyword (plus its friend no) runs conceptually in a BEGIN block.

A do { ... } block provides a neat solution:

package mylib; use constant { MODULE_PATH => __FILE__, CONF_PATH => do { $_ = __FILE__; s/pm$/conf/i; $_ }, }; print CONF_PATH;

If your perl is fairly recent, you can do away with do and use /r.

package mylib; use constant { MODULE_PATH => __FILE__, CONF_PATH => (__FILE__ =~ s/pm$/conf/ir), }; print CONF_PATH;
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'


Comment on Re: BEGIN block and failure to initialize constants
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2014-09-22 08:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (185 votes), past polls