I have the following small Perl (v5.10) program:
use strict;
my @nums;
my $i = 0;
while ($i < 5) {
print "Enter number " . $i+1 . ": ";
$nums[$i] = <STDIN>;
$i++;
}
foreach (@nums) {
chomp $_;
print "$_\t";
}
print "\n";
This is the result of a test run:
1: 2
1: 1
1: 6
1: 3
1: 2
2 1 6 3 2
The problem, as you can see, is that the print statement prompting the user for input isn’t functioning as expected. Instead of “Enter number 1: ” or “Enter number 3:”, e.t.c., I just get “1:”. I didn’t expect this to work to be honest because I know that the + operator has been overloaded for string concatenation in Perl. How do I get around this problem? And what is the reason for it?
+is not overloaded. It is a precedence issue. The expression is parsed asWhich is the same as
You can use
to see how Perl parses your scripts.
Adding parentheses sovles the problem.