in reply to Re: Summing Up Array Elements By Group
in thread Summing Up Array Elements By Group

eval EXPR? oh my! No, use sum!

use List::Util qw( sum ); push @Res, sum splice(@arr,0,3) while @arr;

Replies are listed 'Best First'.
Re^3: Summing Up Array Elements By Group
by targetsmart (Curate) on Jan 22, 2009 at 06:01 UTC
    Thank you, ikegami, but one more question on this,
    I have seen the Util.pm code and I included only the reduce and sum part into the below code, now the code looks like this.
    sub reduce (&@) { my $code = shift; no strict 'refs'; return shift unless @_ > 1; use vars qw($a $b); my $caller = caller; local(*{$caller."::a"}) = \my $a; local(*{$caller."::b"}) = \my $b; $a = shift; foreach (@_) { $b = $_; print ">$code<\n"; $a = &{$code}(); } $a; } use vars qw($a $b); sub sum (@) { reduce { $a + $b } @_ } @arr = (0,0,1, 3,2,0, 1,1,1, 11,100,12); push @Res, sum splice(@arr,0,3) while @arr; print "@Res\n";

    Now I see the magic part is '&{$code}()', could you please explain me about this magic part and tell me how this is better than eval?.

      Converting user inputs to Perl code safely is tricky and if dangerous if you fail. When using sum, nothing from the user is converted to Perl code and executed.