the warning is refering to this line:
print "$grand_total
";
$grand_total has no value (it’s uninitialized) . Your code is not written correctly, as you may have noticed since it prints nothing when run.
this line is properly coded:
my $grand_total = &total(1…1000);
you can leave off the & sign though for cleaner looking code:
my $grand_total = total(1…1000);
the problem begins in sub total(). You are using strict (a good thing!) so $total is not visible outside the sub and you never pass it back to the calling routine, you just have “return;” at the end of the sub, which returns nothing (sort of). But you also have:
my $total += $_;
inside the foreach loop. That is also not correct. $total can’t be seen outside the foreach loop, which is a block:
foreach() {
block of code here
}
this is a scoping problem. Variables only are scoped (visible) to the block they are in when use strict is in place (as it should be).
so you have a scoping problem as well as a problem I’m not sure how it’s called. You can’t say:
my $total += $_;
at least not the way you have it. $total will be redefined each time the loop is run and end up with the last value of $_.
Pass your variable to the sub routine (your list of numbers in this case), initiate $total before the foreach block so it’s scope will also be outside the foreach block but not outside the sub rotuine block, and return the value back to the calling routine:
sub total
{
my $total = 0;
foreach(@_)
{
$total += $_;
}
return($total);
}
my $grand_total = total(1..1000);
print "$grand_total \
";
or more succintly:
sub total
{
my $total = 0;
$total+=$_ for @_;
return($total);
}
my $grand_total = total(1..1000);
print "$grand_total \
";