On Wed, May 27, 2009 at 1:42 PM, Daniel Carrera
<[email protected]> wrote:
> sub postfix:<!> { [*] 1..$^n }
> say 5!;
>
> WOW!! That *IS* cool. Can you explain to me how it works? I figured out
> postfix: myself, but the rest is obscure to me.
Key concepts:
1. placeholder variables. The ^ in $^n means it's a placeholder: no
predeclaration required, and placeholders in an expression are
assigned the passed-in arguments in serial order. (The sub could also
have been written more traditionally as sub postfix:<!>($n) { [*]
1..$n } .)
2. the range operator .. : $x..$y for integers $x and $y generates,
in list context, a list of the integers from $x to $y, inclusive.
3. the reduction meta-operator [...] : [OP](@list) collects the
result of applying OP to the elements of the list in order. That is,
assuming foo() is a binary sub, [foo](1,2,3,4) =
foo(foo(foo(1,2),3),4). So [+](@list) generates a sum of the listed
values, [*] generates their product, etc.
So, given the argument to !:
1. create a list of integers from 1 to that value (1..$^n)
2. multiply them all together ([*])
and of course a sub without an explicit return statement returns the
value of the last expression.
>
>
>> I do think captures are inherently impressive, but not easy to explain...
>
> Got a link?
>
> Daniel.
>
--
Mark J. Reed <[email protected]>