Oct 27, 2003 #1 newtarge ISP Joined Oct 27, 2003 Messages 21 Location US Hi, I have a problem trying to add numbers in an array there is 1 number per line of the array. I want to add all line togather. help!!
Hi, I have a problem trying to add numbers in an array there is 1 number per line of the array. I want to add all line togather. help!!
Oct 27, 2003 #2 raider2001 Technical User Joined Apr 27, 2001 Messages 488 Location US If I understand your explanation correctly, the following should work. Code: $total = 0; foreach $line (@array) { if ($line =~ /(\d+)/) { $total += $1; } } Upvote 0 Downvote
If I understand your explanation correctly, the following should work. Code: $total = 0; foreach $line (@array) { if ($line =~ /(\d+)/) { $total += $1; } }
Oct 27, 2003 #3 chazoid Technical User Joined Dec 2, 2002 Messages 300 Location US for (@array){ $sum += $_; } Upvote 0 Downvote
Oct 27, 2003 #4 icrf Programmer Joined Dec 4, 2001 Messages 1,300 Location US http://search.cpan.org/~gbarr/Scalar-List-Utils-1.13/lib/List/Util.pm Code: use List::Util qw/sum/; $sum = sum @array; ---------------------------------------------------------------------------------- ...but I'm just a C man trying to see the light Upvote 0 Downvote
http://search.cpan.org/~gbarr/Scalar-List-Utils-1.13/lib/List/Util.pm Code: use List::Util qw/sum/; $sum = sum @array; ---------------------------------------------------------------------------------- ...but I'm just a C man trying to see the light
Oct 28, 2003 Thread starter #5 newtarge ISP Joined Oct 27, 2003 Messages 21 Location US Thank you very much Raider2001 it worked well, except if the number had a decimal in it "10.4" would ignore the .4. Upvote 0 Downvote
Thank you very much Raider2001 it worked well, except if the number had a decimal in it "10.4" would ignore the .4.
Oct 28, 2003 #6 raider2001 Technical User Joined Apr 27, 2001 Messages 488 Location US Changing the regular expression should fix that problem. Try the following: Code: $total = 0; foreach $line (@array) { if ($line =~ /(\d+\.*\d*)/) { $total += $1; } } Upvote 0 Downvote
Changing the regular expression should fix that problem. Try the following: Code: $total = 0; foreach $line (@array) { if ($line =~ /(\d+\.*\d*)/) { $total += $1; } }