Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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 (Priest) 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 wandering the Monastery: (5)
As of 2025-11-11 14:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (68 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.