Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding all elements of an array

Status
Not open for further replies.

carpeliam

Programmer
Mar 17, 2000
990
US
I can't remember if there's a shortcut for adding all elements of an array in Perl.. it sounds like the kind of thing that Perl would be able to do, so I thought I'd ask. The quickest way I know is something like this:

my $total_size = 0;
foreach $item (@array) {
$total_size += $item;
}

Is there a quicker way? Thanks.. Liam Morley
lmorley@wpi.edu
"light the deep, and bring silence to the world.
light the world, and bring depth to the silence."
 
You could use map or grep, but I'm not sure that would be any faster:
Code:
my $total_size = 0;
map {$total_size += $_} @array;
or
Code:
my $total_size = 0;
grep {$total_size += $_} @array;
 
You could also use an eval and join.. Like sackyhack, I'm not sure if this is any faster.

eval join '+',@array;

brendanc@icehouse.net
 
I would never have thought of using eval and join! Clever solution, whether it's faster or not.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
For the fun of it, I ran all of these methods through the Benchmark module. It appears that, while it may be a lot smaller, eval is actually the slowest route (by a significant margin). And even though it's usually considered bad form to use it in a void context, grepping was consistently the fastest. Who would've thought?

brendanc@icehouse.net
 
I would have guessed that eval would be the slowest, because of what's involved. I MIGHT have guessed that grep or map would be faster than the for loop, since it would (presumably) be optimized internally. It's nice to know for sure.

Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top