in reply to Re: sum function
in thread sum function

For the else block, it's simpler to iterate over the values() rather than the keys. (Mind the name of the variable...)
else { for (values %$t_hash) { $total += $_ } # (use the statement modifier for if preferred) }
The two blocks could also be combined into a single loop -- whether this is an improvement, I'm not sure. :)
sub sum_hash { my $href = shift; my $total = 0; for ( @_ ? @{$href}{@_} : values %$href ) { $total += $_; } return $total; }
If @_ contains any elements, iterate over a hash slice using the contents of @_ as the keys; otherwise iterate over all the values in the hash.

Replies are listed 'Best First'.
Re: Re: Re: sum function
by ichimunki (Priest) on Dec 26, 2000 at 05:18 UTC
    Chipmunk, I love it. Your second method is especially Perlish.