How can I check (peek) STDIN for piped data in Perl without using select?

后端 未结 2 832
猫巷女王i
猫巷女王i 2021-02-14 14:42

I\'m trying to handle the possibility that no arguments and no piped data is passed to a Perl script. I\'m assuming that if there are no arguments then input is being piped via

2条回答
  •  生来不讨喜
    2021-02-14 15:28

    Perl comes with the -t file-test operator, which tells you if a particular filehandle is open to a TTY. So, you should be able to do this:

    if ( -t STDIN and not @ARGV ) {
        # We're talking to a terminal, but have no command line arguments.
        # Complain loudly.
    }
    else {
        # We're either reading from a file or pipe, or we have arguments in
        # @ARGV to process.
    }
    

    A quick test reveals this working fine on Windows with Perl 5.10.0, and Linux with Perl 5.8.8, so it should be portable across the most common Perl environments.

    As others have mentioned, select would not be a reliable choice as there may be times when you're reading from a process, but that process hasn't started writing yet.

    All the best,

    Paul

提交回复
热议问题