Search code examples
perlstdin

In Perl, how do I determine if there's a standard input present?


I've got a script that grabs standard input:

&process_input

sub process_input {
    while(<STDIN>) {
       $log_data .= $_;
    }
}

When I run the script:

myscript.pl -param1=a -param2=b

I get stuck in this subroutine. Everything runs OK if I do:

echo "" | myscript.pl -param1=a -param2=b

How do I determine if I even have a standard input?

I would have thought that while(<STDIN>) would return false and not run, but I'm guessing it's actually waiting for you to type something in that why it's 'stuck'.


Solution

  • You want to check where your STDIN (STanDard INput) is coming from: another application or a terminal. In your case, it's the second option, causing a read operation to stall the process until the user inputs something. For a solution, see How can I tell if STDIN is connected to a terminal in Perl?.

    if (-t STDIN) {
        # input attached to terminal and will probably ask user
    } else {
        # input from other process
    }
    

    There's also IO::Interactive that might do better/more reliable checking.