in reply to Re: List-to-Scalar Function?
in thread List-to-Scalar Function?

You can also implement reduce in native Perl:
sub reduce (&@) { my $op = shift; no strict 'refs'; my $pkg = caller; local *A = local *{"$pkg\::a"}; $A = shift; local *B = local *{"$pkg\::b"}; foreach $B (@_) { $A = $op->(); } $A; }
(Stolen shamelessly from here, with full permission of the author. :-)

UPDATE
D'oh. I should have read the source-code. They don't present that in the documentation... And I wrote it originally because someone (jcwren I think) was having trouble running my code at Re (tilly) 1: An exercise in "That's not the way I'd do it" (TNTWIDI) because List::Util wasn't compiling.

Replies are listed 'Best First'.
Re: Re (tilly) 2: List-to-Scalar Function?
by merlyn (Sage) on May 09, 2001 at 03:55 UTC
    Somewhat similar to the pure-Perl implementation in List::Util itself...
    use vars qw($a $b); sub reduce (&@) { my $code = shift; return shift unless @_ > 1; my $caller = caller; local(*{$caller."::a"}) = \my $a; local(*{$caller."::b"}) = \my $b; $a = shift; foreach (@_) { $b = $_; $a = &{$code}(); } $a; }
    Although if the XS compiles and loads, this code is not used.

    -- Randal L. Schwartz, Perl hacker