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 $

      🦛