455,848 Members | 1,416 Online Need help? Post your question and get tips & solutions from a community of 455,848 IT Pros & Developers. It's quick & easy.

# sum up array

 P: 72 Hi, I am trying to sum up all the second element in an array (@hello). I tried as below but cant work. Suppose i could get 12 ( 3+ 4 + 5) please guide. thx Expand|Select|Wrap|Line Numbers my @hello =(); push (@hello, join(",", 'A', 3)); push (@hello, join(",", 'B', 4)); push (@hello, join(",", 'C', 5));   \$helo=(@hello);   for(\$y=0;\$y<\$helo;\$y++) { push(@out, pop(@hello[\$y])); } my \$total = 0;  \$total_in_array += \$_ foreach @out ; Apr 11 '08 #1
5 Replies

 Expert 2.5K+ P: 4,059 Your @hello array will have three values: ,A3 ,B4 ,C5 If you wanted to add up the number part of each element of the array you first have to remove the no-digit characters. But I am not sure what you are really trying to do. The use of the join() function appears to be completely wrong since it joins the three things together to make one string, for example ,A3. The use of push and pop is not necessary at all. Apr 11 '08 #2

 P: 72 use Data::Dumper; Expand|Select|Wrap|Line Numbers my @hello =();  # this is just to get a sample data; what i want is to sum up the 2nd element in the array. push (@hello, join(",", 'A', 3)); push (@hello, join(",", 'B', 4)); push (@hello, join(",", 'C', 5));   print Dumper(@hello); exit; Expand|Select|Wrap|Line Numbers \$VAR1 = 'A,3'; \$VAR2 = 'B,4'; \$VAR3 = 'C,5';   from @hello, I wish to get the 2nd element of each array and then sum them up. Means, i would like to add 3+4+5 = 12. Apr 11 '08 #3

 Expert 2.5K+ P: 4,059 Sorry, somehow I misread your code and thought the data would be different, of course it will be as Data dumper shows: \$VAR1 = 'A,3'; \$VAR2 = 'B,4'; \$VAR3 = 'C,5'; in which case you could do this instead of all that unecessary stuff you were doing: Expand|Select|Wrap|Line Numbers my @hello =(); push (@hello, join(",", 'A', 3)); push (@hello, join(",", 'B', 4)); push (@hello, join(",", 'C', 5)); my \$total = 0; for (@hello) {    \$total += (split','); } print \$total; all though I am not sure why you are making this so complicated: Expand|Select|Wrap|Line Numbers push (@hello, join(",", 'A', 3)); push (@hello, join(",", 'B', 4)); push (@hello, join(",", 'C', 5)); just write it as: Expand|Select|Wrap|Line Numbers my @hello = qw (A,3 B,4 C,5); But whatever turns you on mate. It's your code. :) Apr 11 '08 #4

 Expert 2.5K+ P: 4,059 You have some recent threads you posted and never replied to them. If you continue to do that I will no longer help you. That is my personal policy and not the policy of this website. Apr 11 '08 #5

 P: 72 Noted. Sorry.. i will take note next time. Thank you. Apr 11 '08 #6 