Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

How to Test For Empty Piped Input

by roho (Bishop)
on Sep 02, 2024 at 04:39 UTC ( [id://11161507]=perlquestion: print w/replies, xml ) Need Help??

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

I have a test program as shown below. When I pipe data to it, the output displays as expected. When I run the program stand-alone, it silently waits for input. I need a way to test for this condition and exit the program, but so far I can find none. Does anyone know a way of testing for this condition?

Here is the program which I named test.pl:

#!/usr/bin/perl use strict; use warnings; while( <> ) { print $_; }

Note: I'm running on Windows, hence the use of "echo" below to pipe data.

Test #1:
echo a | test.pl (This works as expected)

Test #2:
test.pl (This silently waits for input. I need to test for this condition and exit the program)

"It's not how hard you work, it's how much you get done."

Replies are listed 'Best First'.
Re: How to Test For Empty Piped Input
by parv (Parson) on Sep 02, 2024 at 04:57 UTC

    Before the loop, you could test if standard input connected via pipe (and/or if connected to a tty) via -p (or -t) operator (respectively) (see perldoc -f -x).

    Ah, just noticed that you are running on MS Windows; in that case I have not tested if -[pt] function work reliably or at all.

    You should see some results if you were to search for how to check if the program is connected via pipe.

Re: How to Test For Empty Piped Input
by roho (Bishop) on Sep 02, 2024 at 08:22 UTC
    Thank you for your answers. -t STDIN ... is what I was missing. Working great now! Thanks again.

    "It's not how hard you work, it's how much you get done."

Re: How to Test For Empty Piped Input
by etj (Curate) on Sep 02, 2024 at 07:10 UTC

      Tested now (although not on MSWin32). Works as intended and doesn't even need the BEGIN block.

      #!/usr/bin/env perl use strict; use warnings; die "What no STDIN?\n" if -t; print while <>;

      Runs like this:

      $ ./stdintest.pl What no STDIN? $ echo foo | ./stdintest.pl foo $

      🦛

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11161507]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-09-09 12:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.