如何在不使用select的情况下在Perl中检查(窥视)STDIN中的管道数据? [英] How can I check (peek) STDIN for piped data in Perl without using select?

查看:82
本文介绍了如何在不使用select的情况下在Perl中检查(窥视)STDIN中的管道数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图处理没有参数和管道数据没有传递给Perl脚本的可能性.我假设如果没有参数,则通过STDIN传递输入.但是,如果用户不提供任何参数并且不通过管道将任何内容传递给脚本,它将尝试获取键盘输入.我的目的是提供一条错误消息.

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 STDIN. However if the user provides no arguments and does not pipe anything to the script, it will try to get keyboard input. My objective is to provide an error message instead.

不幸的是,select()不能移植到某些非POSIX系统中. 还有最大的可移植性来做到这一点吗?

Unfortunately, select() is not portable to some non-POSIX systems. Is there another way to do this with maximum portability?

推荐答案

Perl附带了-t file-test运算符,该运算符告诉您特定的文件句柄是否已向TTY打开.因此,您应该可以执行以下操作:

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.
}

一项快速测试表明,在Windows和Perl 5.10.0以及Linux和Perl 5.8.8上都可以正常工作,因此可以在最常见的Perl环境中移植.

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.

正如其他人提到的那样,select并不是一个可靠的选择,因为有时您可能正在从某个流程中读取内容,但是该流程尚未开始编写.

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.

祝一切顺利,

Paul

这篇关于如何在不使用select的情况下在Perl中检查(窥视)STDIN中的管道数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆