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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With