Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^4: How to determine absolute path of current Perl file?

by RonW (Parson)
on Feb 29, 2016 at 21:11 UTC ( [id://1156481]=note: print w/replies, xml ) Need Help??


in reply to Re^3: How to determine absolute path of current Perl file?
in thread How to determine absolute path of current Perl file?

Just FYI, in a module "included" by use, executable statements in "file scope" are being run inside a begin block.

From the documentation for use, use Module LIST; is the same as:

BEGIN { require Module; Module->import( LIST ); }

The reason for using a BEGIN block in a module to execute some code before the module is completely compiled. Even without the BEGIN block, any "file scope" statements will get executed before anything after the use is compiled (then run).

As for the desirability of file scope code in a module, by design, Perl expects a "used" module to run init/sanity-check code at "use time". This is why most modules end with 1;. Perl is expecting the module to "return" a true value if everything is "A-Okay". Otherwise, a false value tells Perl something went wrong. Fetching the current working directory is a reasonable init action. Of course, if you are more comfortable using a BEGIN block, that's fine, too. TIMTOWTDI.

Replies are listed 'Best First'.
Re^5: How to determine absolute path of current Perl file?
by Discipulus (Canon) on Feb 29, 2016 at 22:51 UTC
    thanks for your clarification RonW

    So using a BEGIN block inside a module to be used it's like to say: as soon as possible or even sooner.

    #TestBegin.pm use strict; use warnings; BEGIN{print "inside BEGIN in the module ",__FILE__,"\n"} print "in the module ",__FILE__,"\n"; 1; perl -e "print qq(in the program $0\n);BEGIN{print qq(BEGIN in the pr +ogram $0\n)}" -MTestBegin inside BEGIN in the module TestBegin.pm in the module TestBegin.pm BEGIN in the program -e in the program -e
    And the only possibility to fail is:
    perl -e "print qq(in the program $0\n);BEGIN{print qq(BEGIN in the pr +ogram\n)}use TestBegin;" BEGIN in the program inside BEGIN in the module TestBegin.pm in the module TestBegin.pm in the program -e

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-20 14:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found