If you can store a subroutine in a variable then you can pass said
subroutine to another one as an argument.

This leads us into the joys of functional programming.

And you may have used it already and not even realised.

The .map and .grep methods (and .reduce and bunch of others) all expect a
callable code block (that might be a subroutine) as a function.

This :

my @a = (1..10).map( * ** 2 )

and this :

my &sq = sub ($v) { $v ** 2 };
my @a = (1..10).map( &sq );

are doing the same thing. Except the second one has the &sq function
available for other things.

(A Note on Marc's comment * * * is not the same as -> $x { $x * $x } it is
the same  as -> $x, $y { $x * $y } )

You can then start doing things like storing functions as values in hashes
and doing all *kinds* of fun stuff.

Welcome to the tip of the iceberg.

Simon


On Tue, 11 Feb 2020 at 03:21, ToddAndMargo via perl6-users <
perl6-us...@perl.org> wrote:

> Hi All,
>
> Is Larry using his magic powder again?
>
> Can I declare a subroutine as a variable?
>
>      my $abc = my sub (UInt $u, Str $s, Int $I) {
>
> How would I use it?
>
> And why would do such a thing?
>
> -T
>


-- 
Simon Proctor
Cognoscite aliquid novum cotidie

http://www.khanate.co.uk/

Reply via email to