Tuesday, July 28, 2009

I want to perform a calculation in Perl that should be done with every element in an array. Help?

In other words, say the array is @dollars = "1", "2", "3"; and the equation is:





total of something = some number * exp(every element in the array)





How can I do this? I know I'll need a foreach loop but can I just substitute the array name in where it's supposed to go?

I want to perform a calculation in Perl that should be done with every element in an array. Help?
It’s not 100% clear from your question what you’re after, but I’ll have a crack at it.





Assuming you want to take an array of numbers, multiply each by a given number and total the results, the easiest way is probably:





use List::Util qw( sum );


my $total = sum( map { $_ * $modifier } @array );





I’ve created a full example of the above code at http://pastie.caboo.se/95247





List::Util [1] is a module that provides a few helper functions for operating on lists. sum [2] is one of these, which totals all the items of an array. map [3] is a core function which performs a block of code on every item of an array, returning another array.








Best wishes,


Dave Cardwell.


http://davecardwell.co.uk/perl/
Reply:Does not look easy. May be you can contact a perl expert. Check websites like http://askexpert.info/


No comments:

Post a Comment