How to test for 'being run through require/do'?

J

J Krugman

Is there any way a Perl script can tell whether it is being run
directly from the command line or as the result of a require (or
do) statement in some other Perl script?

TIA!

jill
 
A

Anno Siegel

J Krugman said:
Is there any way a Perl script can tell whether it is being run
directly from the command line or as the result of a require (or
do) statement in some other Perl script?

In short, if all you want to know is if your script is called top level,
check if "caller" returns something true on the scripts top level.

if ( caller ) {
# we're called from somewhere else
} else {
# called top level
}

For more specific aspects, look for "is_require" in perldoc -f caller.

Anno
 
A

Anno Siegel

Jim Gibson said:
Look at the $0 variable to get the name of the Perl file being
executed. If it doesn't match the name of the file doing the looking,
then it wasn't executed directly from the command line.

That is not a recommendable method. Not only is $0 system-dependent,
there are also hard and soft links (and possibly other aliasing methods)
to consider.

Use caller() instead.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top