Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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'

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2016-10-22 00:33 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (291 votes). Check out past polls.