dizzyg has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I'd like to be able to call a script via a browser or via the CLI/shell and have that script 'know' what’s calling it. Also, and more importantly, I’d like for the script to be able to pick up arguments of the form option (i.e. like a simple command-line switch) or option=value ; for instance:

In browser via url:

http://.../script.pl?option1&option2&option3=value3

In CLI:

script.pl option1 option2 option3=value3

I've tried this with CGI and @ARGS but the way either handles switches or assignments is inconsistent and I haven't been able to tell programatically what's calling it.

Cheers

Replies are listed 'Best First'.
Re: Telling if your script is running from web page or CLI
by Anonymous Monk on Sep 29, 2005 at 14:10 UTC
    Although everything can be fooled, heuristics with a good chance of success are:
    • When running from the command line, input/output/stderr will be a terminal (unless redirected), and there will be a controlling terminal.
    • When running as a CGI, several CGI environment variables will be set.
    • When running from a shell, the SHELL environment variable will be set.
    • When running as a CGI, the current UID is a dedicated user ("nobody" for instance).
    • When running from a shell, there will be a home directory.
    • When running as a stand-alone CGI program, the parent process will be the webserver.
    • When running from the shell, the parent, or one of its ancestors will be a shell process.
Re: Telling if your script is running from web page or CLI
by japhy (Canon) on Sep 29, 2005 at 14:04 UTC
    It is possible to have a CGI program have contents in @ARGV. One way is too look for specific keys in (or NOT in) %ENV.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

      I typically look for $ENV{'SERVER_NAME'} or other items that are set automatically by the webserver, with the assumption that most people's shell won't have it set. Another good one to check might be $ENV{'GATEWAY_INTERFACE'}.

        That is not always going to work. If I remember correctly if you run under mod_perl, you start with an extremely limited environment, such as:
        MOD_PERL = mod_perl/2.0.1 MOD_PERL_API_VERSION = 2 PATH = X:\webserver\perl\bin\;C:\WIN ...
        and that's it.

        Checking the environment is probably not very portable either.

        CountZero

        "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Telling if your script is running from web page or CLI
by Zaxo (Archbishop) on Sep 29, 2005 at 23:03 UTC

    You can check whether *STDIN is a tty:

    print -t *STDIN ? "Wow! A real person!\n" : "<p>I feel a distant presence . . .</p>";

    After Compline,
    Zaxo