我正在嘗試編寫一個讀取管道數據的perl腳本,然後根據這些數據提示用戶輸入。下面的腳本,prompt_for_action
,就是我想要做的事:在Perl中讀取STDIN上的管道輸入之後,我可以提示用戶輸入嗎?
#!/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在打破語法高亮系統方面有多出色。 – sidyll 2012-02-28 16:00:50