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

Hello monks,

I know that in most UNIX flavors, there must be a way to determine if the "standard" filehandles are actually standard, or if they are being piped somewhere. For example, when you run the 'ls' command, the default output formatting is different depending on wether you are outputting to the screen or piping the output to some other destination.

The 'more' command is a better example of what I'm doing. It knows wether you have specified a file name command line or wether you are piping its input via STDIN. When it displays the output, it will prompt you to continue after every page, unless you are piping the output into something else.

My question: How do I do this in Perl? I know one solution that some programs use is to require the user to specify a '-' filename whenever using STDIN/STDOUT, but I would like to make this unnecessary in my script.

Thanks in advance for any pointers.

  • Comment on How do I find out if STDIN or STDOUT are attached to a pipe?

Replies are listed 'Best First'.
•Re: How do I find out if STDIN or STDOUT are attached to a pipe?
by merlyn (Sage) on Jun 21, 2002 at 17:02 UTC
Re: How do I find out if STDIN or STDOUT are attached to a pipe?
by broquaint (Abbot) on Jun 21, 2002 at 16:10 UTC
    You can use the -p file test to check whether a filehandle is a pipe e.g
    open(my $handle, "|date") or die("ack - $!"); print '$handle is a pipe', $/ if -p $handle; print while <$handle>; __output__ $h is a pipe Fri Jun 21 17:10:26 GMT 2002
    But AFAIK you can't tell if STDIN has a pipe attached to the other end of it e.g
    echo "foo bar baz" | perl -ne 'print uc' # is the same as (in terms of content) perl -ne 'print uc' foo bar baz ^D
    Which is why the - option is common in many *nix command-line tools.
    HTH

    _________
    broquaint

Re: How do I find out if STDIN or STDOUT are attached to a pipe?
by kjherron (Pilgrim) on Jun 21, 2002 at 20:47 UTC
    The -p file test should work fine on stdin, viz:
    $ sleep 1 | /usr/bin/perl -le 'print -p STDIN' 1 $ /usr/bin/perl -le 'print -p STDIN' < /dev/null $ /usr/bin/perl -v This is perl, version 5.005_03 built for sun4-solaris...
    The same thing happens with a 5.6 binary I have.
Re: How do I find out if STDIN or STDOUT are attached to a pipe?
by grantm (Parson) on Jun 21, 2002 at 21:04 UTC

    Just to expand slightly on merlyn's answer. When you run a script interactively, its STDOUT is attached to a 'TTY', so -t STDOUT would be true.

    When you pipe the output through a pager or redirect it to a file, the -t test would return false. But because a plain file is not a pipe, -p would return false. So in real life, '! -t' is probably used more than '-p'.

A reply falls below the community's threshold of quality. You may see it by logging in.