为什么 STDIN 会导致我的 Perl 程序冻结?
我正在学习 Perl,并编写了这个脚本来练习使用 STDIN。当我运行脚本时,它仅在控制台上显示第一个打印语句。无论我输入什么(包括新行),控制台都不会显示下一个打印语句。 (我在 Windows 计算机上使用 ActivePerl。)它看起来像这样:
$perl script.pl What is the exchange rate? 90.45 [Cursor stays here]
这是我的脚本:
#!/user/bin/perl
use warnings; use strict;
print "What is the exchange rate? ";
my @exchangeRate = <STDIN>;
chomp(@exchangeRate);
print "What is the value you would like to convert? ";
chomp(my @otherCurrency = <STDIN>);
my @result = @otherCurrency / @exchangeRate;
print "The result is @{result}.\n";
在研究我的问题时我注意到的一个潜在解决方案是我可以包括
use IO::Handle;and
flush STDIN; flush STDOUT;in my script. These lines did not solve my problem, though.
我应该怎么做才能让 STDIN 正常工作?如果这是正常行为,我错过了什么?
I am learning Perl and wrote this script to practice using STDIN. When I run the script, it only shows the first print statement on the console. No matter what I type in, including new lines, the console doesn't show the next print statement. (I'm using ActivePerl on a Windows machine.) It looks like this:
$perl script.pl What is the exchange rate? 90.45 [Cursor stays here]
This is my script:
#!/user/bin/perl
use warnings; use strict;
print "What is the exchange rate? ";
my @exchangeRate = <STDIN>;
chomp(@exchangeRate);
print "What is the value you would like to convert? ";
chomp(my @otherCurrency = <STDIN>);
my @result = @otherCurrency / @exchangeRate;
print "The result is @{result}.\n";
One potential solution I noticed while researching my problem is that I could include
use IO::Handle;
and
flush STDIN; flush STDOUT;
in my script. These lines did not solve my problem, though.
What should I do to have STDIN behave normally? If this is normal behavior, what am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当你这样做时
...Perl 等待
EOF
字符(在 Unix 和类 Unix 上是 Ctrl-D)。然后,您输入的每一行(由换行符分隔)都会进入列表。如果您这样做:
...Perl 等待换行,然后将您输入的字符串放入
$answer
中。When you do
...Perl waits for the
EOF
character (on Unix and Unix-like it's Ctrl-D). Then, each line you input (separated by linefeeds) go into the list.If you instead do:
...Perl waits for a linefeed, then puts the string you entered into
$answer
.我发现了我的问题。我使用了错误类型的变量。我不应该写:
我应该使用:
用 $ 而不是 @。
I found my problem. I was using the wrong type of variable. Instead of writing:
I should have used:
with a $ instead of a @.
要结束多行输入,您可以在 Unix 上使用 Control-D 或在 Windows 上使用 Control-Z。
但是,您可能只需要一行输入,因此您应该像其他人提到的那样使用标量。 学习 Perl 将引导您完成此类内容。
To end multiline input, you can use Control-D on Unix or Control-Z on Windows.
However, you probably just wanted a single line of input, so you should have used a scalar like other people mentioned. Learning Perl walks you through this sort of stuff.
您可以尝试启用自动刷新。
要么
这
就是为什么您没有看到打印的输出。
另外,您需要从数组“@”更改为标量变量“$”
You could try and enable autoflush.
Either
or
That's why you are not seeing the output printed.
Also, you need to change from arrays '@' to scalar variables '$'