我的 Perl 程序如何在 Linux 上获取标准输入?
我对 Perl 编程相当陌生,但我对 Linux 有相当多的经验。假设我有以下代码:
while(1) {
my $text = <STDIN>;
my $text1 = <STDIN>;
my $text2 = <STDIN>;
}
现在,主要问题是:Perl 中的 STDIN 是否直接从 Linux 机器上的 /dev/stdin 读取,还是必须通过管道传输 /dev/stdin 到 Perl 脚本?
I am fairly new to Perl programming, but I have a fair amount of experience with Linux. Let’s say I have the following code:
while(1) {
my $text = <STDIN>;
my $text1 = <STDIN>;
my $text2 = <STDIN>;
}
Now, the main question is: Does STDIN in Perl read directly from /dev/stdin on a Linux machine or do I have to pipe /dev/stdin to the Perl script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不向脚本提供任何内容,它会坐在那里等待您输入内容。当您这样做时,它将被放入
$text
中,然后脚本将继续等待您输入内容。当您这样做时,它将进入$text1
。随后,脚本将再次等待您输入内容。完成后,输入将进入$text2
。然后,整个事情就会无限重复。如果您调用脚本,其中
input
是一个文件,脚本将从文件中读取与上面类似的行,然后,当流用完时,将开始分配undef
每个变量在无限的时间内。AFAIK,没有一种编程语言可以从预定义的
STDIN
(或stdin
)文件句柄中读取数据,要求您将程序调用为:If you don't feed anything to the script, it will sit there waiting for you to enter something. When you do, it will be put into
$text
and then the script will continue to wait for you to enter something. When you do, that will go into$text1
. Subsequently, the script will once again wait for you to enter something. Once that is done, the input will go into$text2
. Then, the whole thing will repeat indefinitely.If you invoke the script as
where
input
is a file, the script will read lines from the file similar to above, then, when the stream runs out, will start assigningundef
to each variable for an infinite period of time.AFAIK, there is no programming language where reading from the predefined
STDIN
(orstdin
) file handle requires you to invoke your program as:它直接从 STDIN 文件描述符读取。如果你运行该脚本,它只会等待输入;如果将数据通过管道传输给它,它将循环直到所有数据都被消耗掉,然后永远等待。
您可能希望将其更改为:
这样 EOF 将终止您的程序。
It reads directly from the STDIN file descriptor. If you run that script it will just wait for input; if you pipe data to it, it will loop until all the data is consumed and then wait forever.
You may want to change that to:
so an EOF will terminate your program.
默认情况下,Perl 的 STDIN 仅连接到标准输入文件描述符。除此之外,Perl 并不真正关心数据如何或从哪里来。如果您从管道读取输出、重定向文件或在终端上交互式键入,这与 Perl 相同。
如果您关心每种情况并且希望以不同的方式处理每种情况,那么您可以尝试不同的方法。
Perl's STDIN is, by default, just hooked up to whatever the standard input file descriptor is. Beyond that, Perl doesn't really care how or where the data came from. It's the same to Perl if you're reading the output from a pipe, redirecting a file, or typing interactively at the terminal.
If you care about each of those situations and you want to handle each differently, then you might try different approaches.