6

So I wrote a simple html 1.0 server, and I have some perl scripts on the server. In particular, I have this script called my histogram, that is an html form with a form action equal another cgi file. Here's the code:

print "<form action=\"tallyandprint.cgi\" method=\"GET\">";

Now, when I call tallyandprint.cgi, it plots a graph with gnuplot and sends it to the user's browser (STDOUT is redirected in the html server code, so perl inherets it). Now, I also want to be able to run tallyandprint.cgi from bash, but take a different style of arguments. Right now, I use perl parsing to grab the patterns by parsing the url, and separating the contents between the + symbol (example:?pattern=1+2+3+4 is what the url is).

Thats fine and dandy, but I don't want my arguments to be written in bash as 1+2+3+4, but rather separated differently. I tried to use perl's version of isatty(), but since the input is always from the terminal (because the server executes it), I cannot distinguish between whether the input is from bash or from web browser this way.

My next though was to find out if STDOUT is redirected. Since if the webserver runs the cgi, the STDOUT will be redirected to the socket that the user is connected to. If run in bash, the STDOUT should be the normal tty. How can I check this in perl?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
KrisSodroski
  • 2,796
  • 3
  • 24
  • 39
  • 6
    A better solution is probably to just check if `$ENV{GATEWAY_INTERFACE}` is set. If you're running under CGI, it will be, if you're running from the shell, it shouldn't be. – cjm May 06 '12 at 22:22
  • 1
    http://stackoverflow.com/questions/1914966/how-can-i-determine-if-a-script-was-called-from-the-command-line-or-as-a-cgi-scr http://stackoverflow.com/questions/3086655/in-perl-how-to-distiniguish-between-cli-cgi-mode http://stackoverflow.com/questions/4853948/how-can-i-tell-if-a-perl-script-is-executing-in-cgi-context – daxim May 07 '12 at 07:13
  • Possible duplicate of [How do I detect if stdout is connected to a tty in Perl?](http://stackoverflow.com/questions/3517250/how-do-i-detect-if-stdout-is-connected-to-a-tty-in-perl) – Michael Hampton Mar 19 '16 at 00:39

1 Answers1

10
if (-t STDOUT) {
    say "STDOUT is probably not redirected";
}
else {
    say "STDOUT is probably redirected";
}
salva
  • 9,943
  • 4
  • 29
  • 57
  • 6
    This idiom has been packaged as [IO::Interactive](http://p3rl.org/IO::Interactive). It handles a few unmentioned edge-cases so that we can eliminate the uncertainty from the answer. -- See *[How do I find out if I'm running interactively or not?](http://learn.perl.org/faq/perlfaq8.html#How-do-I-find-out-if-Im-running-interactively-or-not-)* in `perlfaq8`. – daxim May 07 '12 at 07:12