sub total { my $number; foreach (@_) { # you are allowing input from STDIN which is going to # add a \n on the end. So you're going to have to add # a chomp chomp; # UPDATE: ysth is correct, but I'll leave it in # for the next line I added next if (!/^[+-]?[[:digit:].]+$/); # UPDATE: This is slightly better # $number += @_[$_]; # $_ is assigned the value of the element in @_ not the index # So you want $number += $_; } return $number; } my @fred = qw{ 1 3 5 7 9 }; my $fred_total = &total(@fred); # & not required print "The total of \@fred is $fred_total.\n"; print "Enter some numbers on separate lines: \n"; my $user_total = &total(<STDIN>); print "The total of those numbers is $user_total.\n\n";
In reply to Re: Having problems with addition in sub
by grep
in thread Having problems with addition in sub
by bluethundr
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |