在Perl的STDIN上读取管道输入后,我可以提示用户输入吗? [英] Can I prompt for user input after reading piped input on STDIN in Perl?

查看:141
本文介绍了在Perl的STDIN上读取管道输入后,我可以提示用户输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a perl script that reads piped data, then prompts the user for input based on that data. The following script, prompt_for_action, is what I am trying to do:

#!/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";
}

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

but when I run it there is no waiting for user input, it just blows through without waiting for me to type:

$ 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读取我的数据...

If I don't read my data from 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,然后提示用户输入?

Is piping to STDIN and then prompting for user input possible? If so how?

推荐答案

在Unix-y系统上,可以打开 / dev / tty 用于阅读的伪文件。

On Unix-y systems, you can open the /dev/tty pseudo-file for reading.

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";

这篇关于在Perl的STDIN上读取管道输入后,我可以提示用户输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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