Perl脚本不打印< STDIN>多次 [英] Perl script does not print <STDIN> multiple times

查看:57
本文介绍了Perl脚本不打印< STDIN>多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Perl脚本:

I've got this Perl script:

#!/usr/bin/perl
use strict;
use warnings;

print <STDIN>, "\n";
print <STDIN>, "\n";
print <STDIN>, "\n";
print <STDIN>, "\n";
print <STDIN>, "\n";

我将"Hello"传递给脚本的标准输入:

And I'm passing "Hello" to the script's standard input:

echo "Hello" | perl test.pl

我希望它打印"Hello"五次,但它只打印"Hello",后跟五个换行符.谁能解释为什么这不能按预期进行?

I'm expecting it to print "Hello" five times, but it just prints "Hello" followed by five newline characters. Can anyone explain why this wouldn't work as intended?

推荐答案

print <STDIN>, "\n";

<STDIN>(即 readline(STDIN) )在列表上下文中读取,直到到达文件末尾并返回行列表."

<STDIN> (i.e. readline(STDIN)) "in list context reads until end-of-file is reached and returns a list of lines."

在您的程序中,第一个print因此会打印 all 行,这些行是从STDIN读取的行.

In your program, the first print therefore prints all the lines read from STDIN.

根据定义,由于STDIN在列表上下文中读取了要读取的所有内容,因此不再有来自STDIN的行.

By definition, there are no more lines coming from STDIN, because <STDIN> in list context read everything there was to read.

如果您想从STDIN中读取五行并打印它们,则需要:

If you want to read five consecutive lines from STDIN and print them, you need:

print scalar <STDIN>;
print scalar <STDIN>;
print scalar <STDIN>;
print scalar <STDIN>;
print scalar <STDIN>;

根据定义,一行以换行符结尾.如果您不删除它,则无需钉在另一个钉子上.

By definition, a line ends with a newline. If you do not remove it, there is no need to tack on another.

me 来说,将<STDIN>表示的值存储到内存中的某个位置会更直观

It's more intuitive to me that the value represented by <STDIN> is held somewhere in memory once it's piped into the script

您的程序不包含存储从STDIN读取的输入的指令.它所做的就是读取STDIN上的所有可用内容,将其打印并丢弃.

Your program contains no instructions to store the input read from STDIN. All it does is to read everything available on STDIN, print all of it, and discard it.

如果要存储从STDIN中读取的所有内容,则必须明确地进行存储.这就是计算机程序的工作方式:它们完全按照所告诉的那样工作.想象一下,如果计算机程序根据编写或运行它们的人的直觉来做不同的事情,那将是一场灾难.

If you wanted to store everything you read from STDIN, you have to explicitly do so. That's how computer programs work: They do exactly as they are told. Imagine what a disaster it would be if computer programs did different things depending on the intuition of the person writing or running them.

当然,来自STDIN的数据可能是无界的.在那种情况下,将所有内容存储在某个地方是不现实的.

Of course, the data coming from STDIN might be unbounded. In that case, storing all of it somewhere is not going to be practical.

这篇关于Perl脚本不打印&lt; STDIN&gt;多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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