in reply to Detection of main script / libraries

The trick is to use the caller function. Example:

a.pl: unless (caller[0] =~ /main/) { print "a was called directly\n"; }
b.pl:do "a.pl";

Now, if a.pl is called directly, it will print the message, but if b.pl is called first, and a.pl is called from b.pl, it will not print the message.

Replies are listed 'Best First'.
Re: Re: Detection of main script / libraries
by johannz (Hermit) on Mar 25, 2002 at 19:17 UTC

    As a concrete example of this:

    My::Standalone.pm
    unless (caller() =~ /main/) { My::Standalone->run(); } else { @My::Standalone::EXPORT = qw[run]; } package My::Standalone; use strict; use warnings; use Exporter; our @ISA = qw(Exporter); sub run { my($self) = shift || caller(); print "See, I do something\n"; } 1;

    You can then call this with any of the following:

    • perl My/Standalone.pm
    • perl -MMy::Standalone -e"run();"

    or include it in a script:

    test.pl
    #!perl use strict; use warnings; use My::Standalone; print "Do something\n"; run(); # Call the run function exit;