http://qs321.pair.com?node_id=698922

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

Seems like there should be an existing snippet for this but I couldn't find it. I want my script to have a few different connect methods, either TCP socket, CGI script, or run from command line. Is there a well established way for my script to know how it was invoked and can the "use" instructions be made conditional on the mode of invocation?

Replies are listed 'Best First'.
Re: How was my script launched?
by gaal (Parson) on Jul 20, 2008 at 17:25 UTC
    It's not the socket that invokes your script, it's a web server or some other server process. Perhaps you can configure them to pass a command line argument. In the case of CGI, you typically have cgi environment variables set up for you that you might try to detect.

    In many cases, you can replace "use" with runtime "require Foo; Foo->import(ARGS)", which you can of course predicate on the method you detected you were called with. Best.pm also has some goodies for conditional module loading that may suit your needs.

Re: How was my script launched?
by pc88mxer (Vicar) on Jul 20, 2008 at 18:48 UTC
    How about using the -S and -p operators on STDIN?

    If your program was invoked by a TCP server (like inetd), then -S STDIN should be true. If it was invoked by a web server then -p STDIN is likely to be true (check this). And if it is taking input from a user then -t STDIN (or perhaps -c STDIN) should be true.

    You can also check for environment variables to help decide how you were invoked. For instance, if you are being invoked as a CGI script, the web server will set up a lot of variables that won't be set if you are handling the connection yourself. Same for an interactive session.

Re: How was my script launched?
by Perlbotics (Archbishop) on Jul 20, 2008 at 18:54 UTC
    Additionally, you might get some further clues from inspecting the filename ($0) or the command line arguments (@ARGV). If your OS supports symbolic links, than aliasing your script by symlinking it might be another alternative to identify launch circumstances. E.g., if you symlink yourscript.pl to alt_name.pl and then call the latter,  $0 =~ m{/alt_name\.pl$} will render true, at least under *NIX.