【问题标题】:Perl script does not print <STDIN> multiple timesPerl 脚本不会多次打印 <STDIN>
【发布时间】:2017-07-19 13:42:50
【问题描述】:

我有这个 Perl 脚本:

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

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

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

echo "Hello" | perl test.pl

我希望它打印“Hello”五次,但它只打印“Hello”后跟五个换行符。谁能解释为什么这不能按预期工作?

【问题讨论】:

  • perl 中的 是一个文件描述符,每个标准输入只能读取一次。
  • 嗯...我想将&lt;STDIN&gt; 分配给标量变量会更有意义。为什么我不能多读一遍?
  • 管道就是这样工作的。读完之后,就没有了。实际上这就是文件的一般工作方式——它们有一个结尾,当你到达结尾时,重复读取操作不会跳回到开头,即使在确实有能力返回的文件上也是如此。您知道哪种语言可以通过再次说“阅读”来重复阅读相同的输入?
  • @KaushikNayak STDIN 指的是一个裸字文件句柄,而不是一个描述符。 &lt;STDIN&gt;readline(STDIN),这也不是描述符。
  • @思南。谢谢 !。向你学习很棒的 Perl 东西很好

标签: bash perl


【解决方案1】:
print <STDIN>, "\n";

&lt;STDIN&gt;(即readline(STDIN))“在列表上下文中读取,直到到达文件末尾并返回行列表。”

因此,在您的程序中,第一个 print 会打印 allSTDIN 读取的行。

根据定义,不再有来自STDIN 的行,因为&lt;STDIN&gt; 在列表上下文中读取了所有要读取的内容。

如果你想从STDIN读取连续的五行并打印出来,你需要:

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

根据定义,一行以换行符结束。如果你不删除它,就没有必要再粘上另一个了。

更直观的是,&lt;STDIN&gt; 表示的值一旦通过管道传输到脚本中就会保存在内存中的某个位置

您的程序不包含存储从STDIN 读取的输入的指令。它所做的只是阅读STDIN 上的所有内容,打印所有内容,然后丢弃。

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

当然,来自STDIN 的数据可能是无限的。在这种情况下,将所有内容存储在某个地方是不切实际的。

【讨论】:

  • 这更有意义 - 我不知道 &lt;STDIN&gt;readline(STDIN) 的别名。谢谢!
【解决方案2】:

如果您想循环打印用户定义的文本次数, 你可以像这样使用 do while 循环:

#!/usr/bin/env perl
#Program: stdin.pl
use strict;
use warnings;
use feature 'say'; # like print but automatic ending newline.

my $i = 1; # Our incrementer.
my $input; # Our text from standard input that we want to loop.
my $total; # How many times we want to print the text on a loop.

say "Please provide the desired text of your standard input.";
chomp($input = <STDIN>); # chomp removes a newline from the standard input. 
say "Please provide the amount of times that you want to print your standard input to the screen.";
chomp($total = <STDIN>);
say ">>> I'm in your loop! <<<"; 
do # A do while loop iterates at least once and up to the total number of iterations provided by user. 
{
say "Iteration $i of text: $input";
$i++;
}while($i <= $total);
say ">>> I'm out of your loop! <<<";

这是我在标准输入中使用“Hello”和“8”执行代码时得到的结果:

> perl .\stdin.pl
Please provide the desired text of your standard input.
Hello!
Please provide the amount of times that you want to print your standard input to the screen.
8
>>> I'm in your loop! <<<
Iteration 1 of text: Hello!
Iteration 2 of text: Hello!
Iteration 3 of text: Hello!
Iteration 4 of text: Hello!
Iteration 5 of text: Hello!
Iteration 6 of text: Hello!
Iteration 7 of text: Hello!
Iteration 8 of text: Hello!
>>> I'm out of your loop! <<<

【讨论】:

  • 这并没有解决我的问题——我不是在寻求替代方案,我是在问为什么我写的代码不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
相关资源
最近更新 更多