samgardner
Programmer
I'm going through the exercises in Llama, and have come on an odd phenomenon. The code seems to be completely skipping the first print call. However the first function call to &total succeeds (I know because my previous code hadn't set the value of $total to zero at the start of the sub, and it added all the values 1 to 1000 plus whatever the user had entered). Here's my code:
#!perl -w
sub total {
$total = 0;
foreach $_(@_){
$total += $_;
}
$total;
}
print "type a list of numbers on separate lines\n";
chomp(@nums=<STDIN>);
$return = &total(@nums);
print "the returned value is $return"."\n";
$return=&total(1..1000);
print "the sum of 1 to 1000 is $return"."\n";
The output is like:
type a list of numberson separate lines
2
3
4
3
4
3
the sum of 1 to 1000 is 500500
If I don't set the value of $total to zero, the last line is "the sum of 1 to 1000 is 500519"
1: I don't understand why it's skipping the first print call. Does anyone?
2: I don't know how to properly get the $total variable to be treated as a lexical variable. If I use the my keyword, it will apply to the variable within the foreach loop and thus return undef. I had been under the impression that sub variables were lexical anyway, but that seems to be mistaken.
Appreciate any help/advice;
s
#!perl -w
sub total {
$total = 0;
foreach $_(@_){
$total += $_;
}
$total;
}
print "type a list of numbers on separate lines\n";
chomp(@nums=<STDIN>);
$return = &total(@nums);
print "the returned value is $return"."\n";
$return=&total(1..1000);
print "the sum of 1 to 1000 is $return"."\n";
The output is like:
type a list of numberson separate lines
2
3
4
3
4
3
the sum of 1 to 1000 is 500500
If I don't set the value of $total to zero, the last line is "the sum of 1 to 1000 is 500519"
1: I don't understand why it's skipping the first print call. Does anyone?
2: I don't know how to properly get the $total variable to be treated as a lexical variable. If I use the my keyword, it will apply to the variable within the foreach loop and thus return undef. I had been under the impression that sub variables were lexical anyway, but that seems to be mistaken.
Appreciate any help/advice;
s