in reply to Summing Up Array Elements By Group

I might not be effective!, but a solution here.
my @arr = (0,0,1, 3,2,0, 1,1,1, 11,100,12); push (@Res, eval join("+",splice(@arr,0,3))) while (@arr/3); print "@Res";

Replies are listed 'Best First'.
Re^2: Summing Up Array Elements By Group
by ikegami (Patriarch) on Jan 21, 2009 at 14:58 UTC

    eval EXPR? oh my! No, use sum!

    use List::Util qw( sum ); push @Res, sum splice(@arr,0,3) while @arr;
      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.