b4swine has asked for the wisdom of the Perl Monks concerning the following question:
It works. My question is how can I get it to have semantics exactly like sort?=usage reduce \&f @x; eg. reduce {$a+$b} @x; # sum @x reduce {$a*$b) 1..7 # factorial(7) = 7! =cut sub reduce (&@) { my $f = shift; local ($a, $b) = shift; $a=&$f while $b=shift; return $a; } my $x = reduce { $a*$b } 1..7; print $x;
If the subroutine's prototype is ($$), the elements to be compared are passed by reference in @_, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b.
SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use.
moritz and duelafn seem to have addressed most of the issues.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to get sort-like semantics? (\&f)
by tye (Sage) on Oct 25, 2007 at 15:47 UTC | |
|
Re: How to get sort-like semantics?
by duelafn (Parson) on Oct 25, 2007 at 12:51 UTC | |
by friedo (Prior) on Oct 25, 2007 at 13:59 UTC | |
by duelafn (Parson) on Oct 26, 2007 at 19:55 UTC | |
|
Re: How to get sort-like semantics?
by moritz (Cardinal) on Oct 25, 2007 at 12:47 UTC | |
by princepawn (Parson) on Oct 25, 2007 at 15:30 UTC | |
|
Re: How to get sort-like semantics?
by FunkyMonk (Bishop) on Oct 25, 2007 at 14:22 UTC | |
|
Re: How to get sort-like semantics?
by jdporter (Paladin) on Oct 25, 2007 at 12:38 UTC | |
by ForgotPasswordAgain (Vicar) on Oct 25, 2007 at 17:24 UTC | |
|
Re: How to get sort-like semantics?
by ikegami (Patriarch) on Oct 25, 2007 at 19:47 UTC | |
by ikegami (Patriarch) on Oct 25, 2007 at 20:54 UTC |