Thursday, July 30, 2009

In Perl, how do I add elements of an array using a loop?

Using Perl:





I tried using a for loop but it keeps printing out the last element in the array with the total. (i.e. "410" 4 is the last element and 10 is the total)





for($i=$#ARGV; $i%26gt;=0; $i--)


{$sum += $ARGV[$i];}


print "$sum\n";





Furthermore, how would I pass @ARGV to a subroutine and what would the "function" call in the main program look like?

In Perl, how do I add elements of an array using a loop?
Is there a particular reason you want to process the array in reverse? You should avoid $# if at all possible. map is an elegant way to process all elements of an array:





my $iSum = 0;


map { $iSum += $_ } @ARGV;


print "$iSum\n";





You can pass @ARGV to a function like this:





my_function(@ARGV);


sub my_function


{


local $" = ',';


print "my_function got args (@_)\n";


}
Reply:first off i ran that loop exactly as is and it worked fine, i put in 1 2 3 4 and got out 10 not 410. so im not sure why it isnt working for you. i really did run character for character the same loop.





as far as passing @ARGV to a subroutine, you could do this:





print sum(@ARGV);





sub sum {


while ($num = shift) {$total += $num}


return $total;


}
Reply:you need to use while or do loop.


No comments:

Post a Comment