Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How was my script launched?

by Chosen Typist (Initiate)
on Jul 20, 2008 at 16:12 UTC ( #698922=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://698922]
Approved by Erez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2021-04-19 23:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?