Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
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 about the Monastery: (12)
As of 2014-07-28 19:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (207 votes), past polls