【问题标题】:Can I prompt for user input after reading piped input on STDIN in Perl?在 Perl 中读取 STDIN 上的管道输入后,我可以提示用户输入吗?
【发布时间】:2012-03-18 01:43:26
【问题描述】:

我正在尝试编写一个读取管道数据的 perl 脚本,然后根据该数据提示用户输入。以下脚本,prompt_for_action,是我想要做的:

#!/usr/bin/perl 

my @hosts = ();
while (<>) {
    my $host = $_;
    $host =~ s/\n//; # strip newlines
    push(@hosts, $host);
}

for my $host (@hosts) {
    print "Do you want to do x with $host ? y/n: ";
    chomp(my $answer = <>);
    print "You said `$answer`.\n";
}

但是当我运行它时,没有等待用户输入,它只是吹过而不等待我输入:

$ echo "test1.example.com
> test2.example.com" | ./prompt_for_action
Do you want to do x with test1.example.com ? y/n: You said ``.
Do you want to do x with test2.example.com ? y/n: You said ``.

如果我不从 STDIN 读取我的数据...

#!/usr/bin/perl 

my @hosts = ('test1.example.com', 'test12.example.com');

for my $host (@hosts) {
    print "Do you want to do x with $host ? y/n: ";
    chomp(my $answer = <>);
    print "You said `$answer`.\n";
}

然后脚本工作正常:

$ ./prompt_for_action 
Do you want to do x with test1.example.com ? y/n: y
You said `y`.
Do you want to do x with test12.example.com ? y/n: n
You said `n`.

是否可以通过管道连接到 STDIN,然后提示用户输入?如果有怎么办?

【问题讨论】:

  • Perl 在打破语法高亮系统方面的出色表现令人难以置信。

标签: perl command-line stdin


【解决方案1】:

在 Unix-y 系统上,您可以打开 /dev/tty 伪文件进行读取。

while (<STDIN>) {
    print "from STDIN: $_";
}
close STDIN;

# oops, need to read something from the console now
open TTY, '<', '/dev/tty';
print "Enter your age: ";
chomp($age = <TTY>);
close TTY;
print "You look good for $age years old.\n";

【讨论】:

  • 我只能关闭 STDIN,然后:打开 STDIN、“
【解决方案2】:

对于非 Unix-y 系统,您可以使用来自 Term::ReadLinefindConsole,然后像在 mob's answer 中一样使用其输出,例如而不是 /dev/tty 放入 findConsole 第一个元素的输出。

Windows 上的示例:

use Term::ReadLine;
while (<STDIN>) {
    print "from STDIN: $_";
}
close STDIN;

# oops, need to read something from the console now
my $term = Term::ReadLine->new('term');
my @_IO = $term->findConsole();
my $_IN = $_IO[0];
print "INPUT is: $_IN\n";
open TTY, '<', $_IN;
print "Enter your age: ";
chomp($age = <TTY>);
close TTY;
print "You look good for $age years old.\n";

输出:

echo SOME | perl tty.pl
from STDIN: SOME
INPUT is: CONIN$
Enter your age: 12 # you can now enter here!
You look good for 12 years old.

【讨论】:

    【解决方案3】:

    一旦您通过 STDIN 进行管道传输,您之前的 STDIN(键盘输入)就会被管道替换。所以我认为这是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-13
      • 2016-06-05
      • 2017-02-10
      • 2011-01-29
      • 2013-11-04
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多