Why does STDIN cause my Perl program to freeze?

I study Perl and wrote this script for practice using STDIN. When I run the script, it only displays the first print statement on the console. No matter what I type, including newlines, the console does not display the next print statement. (I am 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 of the possible solutions that I noticed while researching my problem is to enable

  use IO :: Handle; 
and
  flush STDIN;  flush STDOUT; 
in my script. However, these lines did not help solve my problem.

What to do if STDIN behaves normally? If this is normal behavior, what am I missing?

+7
perl stdin activeperl
source share
4 answers

When you do

 my @answer = <STDIN>; 

... Perl is waiting for the EOF character (on Unix and Unix - like Ctrl-D). Then, each line you enter (separated by linear translations) is included in the list.

If you do the following:

 my $answer = <STDIN>; 

... Perl waits for the line feed, then puts the line you entered in $answer .

+18
source share

I found my problem. I used the wrong type of variable. Instead of writing:

 my @exchangeRate = <STDIN>; 

I should have used:

 my $exchangeRate = <STDIN>; 

with $ instead of @.

+5
source share

To complete multiline input, you can use Control-D for Unix or Control-Z on Windows.

However, you probably only need one line of input, so you should use a scalar, as other people mentioned. Learning Perl will help you with this.

+4
source share

You can try to enable autorun.

Or

 use IO::Handle; STDOUT->autoflush(1); 

or

 $| = 1; 

That is why you do not see the output printed.

In addition, you need to switch from the '@' arrays to the '$' scalar variables

 $val = <STDIN>; chomp($val); 
-3
source share

All Articles