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

Discussion in 'Perl Misc' started by J Krugman, Jan 25, 2005.

  1. J Krugman

    J Krugman Guest

    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
    --
    To s&e^n]d me m~a}i]l r%e*m?o\v[e bit from my a|d)d:r{e:s]s.
     
    J Krugman, Jan 25, 2005
    #1
    1. Advertising

  2. J Krugman

    Anno Siegel Guest

    J Krugman <> wrote in comp.lang.perl.misc:
    >
    >
    > 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
     
    Anno Siegel, Jan 25, 2005
    #2
    1. Advertising

  3. J Krugman

    Anno Siegel Guest

    Jim Gibson <> wrote in comp.lang.perl.misc:
    > In article <ct64bt$4ok$>, J Krugman
    > <> wrote:
    >
    > > 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?

    >
    > 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
     
    Anno Siegel, Jan 25, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. slamdunk
    Replies:
    3
    Views:
    289
    Martin Vilcans
    Jul 10, 2009
  2. Skybuck Flying

    Call oddities: &Test() vs &Test vs Test

    Skybuck Flying, Oct 4, 2009, in forum: C Programming
    Replies:
    1
    Views:
    726
    Skybuck Flying
    Oct 4, 2009
  3. Sean O'Dell

    Test::Unit non-auto-run test case?

    Sean O'Dell, Sep 18, 2003, in forum: Ruby
    Replies:
    1
    Views:
    114
    Sean O'Dell
    Sep 18, 2003
  4. nicknameoptional
    Replies:
    2
    Views:
    98
    nicknameoptional
    Jan 24, 2006
  5. Fernando Perez
    Replies:
    3
    Views:
    97
    Fernando Perez
    Apr 17, 2009
Loading...

Share This Page