Terminal Or Web

1 minute read

here is a fun little ditty. Not really sure the usefullness of this but interesting all the same.

OK, So here it is. you have a script that prints out some sort of data. This is a pretty straight forward script. I called mine test_print.pl

#!/usr/bin/perl

use strict;
use warnings;

print "Printing some data. \n";

exit;

Now if you run this from a command line or terminal like below, you would get the following.

$ perl test_print.pl
Printing some data
$

But if you called that same script from a web browser. It would look like this. Internal Server Error

No problem, we just add this line to the script.

print "Content-type: text/html\n\n";

So our code now looks like this.

#!/usr/bin/perl

use strict;
use warnings;

print "Content-type: text/html\n\n";
print "Printing some data. \n";

exit;

This will now give us this when run from a browser. Browser Working

But if we now run it from the command line or terminal again we get this.

$ perl test_print.pl
Content-type: text/html

Printing some data.
$

Still works but gives me the ugly line of Content-type: text/html Ahh but there is a way. Lets check to see if the script is being run from a web browser or terminal.

First thing I do is create a sub routine that will open a file handle to the terminal output. If that is successfull we get true if not false.

sub isatty() { 
  no autodie;
  return open(my $tty, '+<', '/dev/tty');
}

I then will check if the sub returns a value, if not I will assume it is being run from a browser and print the Content type header. If I do get a value I assume it is being run from a terminal and will not print the header.

if (!isatty()) { print "Content-type: text/html\n\n"; }

So here is the final script that will print data out either to the browser or a terminal.

#!/usr/bin/perl

use strict;
use warnings;

sub isatty() { 
  no autodie;
  return open(my $tty, '+<', '/dev/tty');
}

if (!isatty()) { print "Content-type: text/html\n\n"; }

print "Printing some data. \n";

exit;

Categories:

Updated: