Reputation:
"ls" behaves differently when its output is being piped:
> ls ???
bar foo
> ls ??? | cat
bar
foo
How does it know, and how would I do this in Perl?
Upvotes: 12
Views: 221
Reputation: 118665
In Perl, the -t
file test operator indicates whether a filehandle
(including STDIN
) is connected to a terminal.
There is also the -p
test operator to indicate whether a filehandle
is attached to a pipe.
$ perl -e 'printf "term:%d, pipe:%d\n", -t STDIN, -p STDIN'
term:1, pipe:0
$ perl -e 'printf "term:%d, pipe:%d\n", -t STDIN, -p STDIN' < /tmp/foo
term:0, pipe:0
$ echo foo | perl -e 'printf "term:%d, pipe:%d\n", -t STDIN, -p STDIN'
term:0, pipe:1
File test operator documentation at perldoc -f -X
.
Upvotes: 13
Reputation: 50667
use IO::Interactive qw(is_interactive);
is_interactive() or warn "Being piped\n";
Upvotes: 6