in reply to Having problems with addition in sub

You have two a syntax mistake s in your foreach .
UPDATE: ysth is correct about the chomp. It was uneeded as my code was orginally posted
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";


grep
Mynd you, mønk bites Kan be pretti nasti...

Replies are listed 'Best First'.
Re^2: Having problems with addition in sub
by ysth (Canon) on Oct 01, 2006 at 03:51 UTC
    Trailing (and leading, for that matter) whitespace is ignored (with no warning) when you use a string in numeric context, so there's no need for the chomp.