【发布时间】: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