Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2017-02-23 13:23 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (347 votes). Check out past polls.