I have the following script:
use 5.12.4;
use strict;
use warnings;
say "Enter a functionality:";
while (<>) {
if (/add/) {
say "Enter your numbers:";
my @a = (<>);
my $sum += $_ for @a;
say $sum;
}
}
When I run this program, it prompts:
Enter a functionality:
I enter add and it says:
Enter your numbers:
I enter several numbers on separate lines of input follow by the [ctrl]Z and get the following error:
Use of uninitialized value $sum in say at C:\myperl\Math-Master\math-master.pl l
ine 11, <> line 9.
Why doesn’t my code add all of the input? Why does this error come?
You cannot use a postscript loop on a declaration statement. The variable
$sumis supposed to be incremented each loop, which it cannot be in the same statement it is being declared. You must first declare it, then assign to it with a postscript loop:You might consider using List::Util for this, and skipping the temp variable
@a. And moving thesayinside the while loop:But that is a bit clunky. Why not:
That way, you do not have to press ctrl-Z (ctrl-D) to stop the input.