GigaRohan
GigaRohan

Reputation: 747

In Perl, how to use plus operator for arithmetic calculation in print statement?

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?

Upvotes: 3

Views: 6735

Answers (2)

raina77ow
raina77ow

Reputation: 106365

Although your immediate problem is incorrect assumption of operator precedence, I see another two (potential) issues that might be interesting as well.

First, it makes little sense using $i + 1, when you can just start your 'output' index from 1, end with 5, but use push to fill the array instead.

Second, it's a bit weird seeing chomp at the output phase of the script, where in fact it should be done in the input phase (as you try to collect numbers from user, don't you?)

For example:

use warnings; use strict;

my @numbers;
for my $i (1..5) {
  print "Enter number $i: ";
  chomp(my $number = <STDIN>);
  push @numbers, $number;
}

print "$_\t" for @numbers;
print "\n";

Upvotes: 5

choroba
choroba

Reputation: 241758

+ is not overloaded. It is a precedence issue. The expression is parsed as

print(((('Enter number ' . $i) + 1) . ': '));

Which is the same as

print((0 + 1) . ': ');

You can use

perl -MO=Deparse,-p -e 'print "Enter number " . $i+1 . ": ";'

to see how Perl parses your scripts.

Adding parentheses sovles the problem.

Upvotes: 8

Related Questions