Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple perl addition program going wrong?

Tags:

perl

Hi i am a novice perl learner this simple perl program

$inputline= <STDIN>;
print "first input";
print( $inputline); 
$inputline=<STDIN>;
print "second input";
print($inputline);
$sum= $inputline+$inputline;
print"sum 1stinput and 2ndinput";
print($sum);

output

perl count.pl
3
4
first input3
second input4
sum 1stinput and 2ndinput : 8

why is the output 8 instead of being 7?

like image 862
learningMatlab Avatar asked Jan 30 '26 08:01

learningMatlab


1 Answers

Because you add $inputline to itself when it is 4.

If you want to sum the two inputs, you either have to do it with two variables, or do the addition before the variable changes. E.g.:

my $input1 = <>;
my $input2 = <>;
my $sum = $input1 + $input2;
print "Sum: $sum";

Or

my $input = <>;
my $sum = $input;
$input = <>;
$sum += $input;
print "Sum: $sum";

You could do something simpler, such as:

perl -nlwe '$sum += $_; print "Sum: $sum";'

Which is basically the equivalent of:

use strict;
use warnings; # always use these

my $sum;
while (<>) {  # your input
    $sum += $_;
    print "Sum: $sum\n";
}

Use Ctrl-C or Ctrl-D to break out of the loop (Ctrl-Z in windows).

like image 85
TLP Avatar answered Feb 01 '26 23:02

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!