5.6 Anonymous Subroutines

     

Anonymous subroutines do everything that ordinary subroutines do. They can declare a formal parameter list with optional and required parameters, take positional and named arguments, and do variadic slurping . The only difference is that they don't define a name. But since you can't call a subroutine if you have no way to refer to it, they have to get the equivalent of a name somewhere, whether they're assigned to a variable, passed as a parameter, or aliased to another subroutine.

 $make_tea = sub ($tealeaves, ?$sugar, ?$milk) { . . . } 

The arrow operator used with for and given is just another way of defining anonymous subroutines. The arrow doesn't require parentheses around its parameter list. It can't declare named subs, and can't declare a return type.

 $make_tea = -> $tealeaves, ?$sugar, ?$milk { . . . } 

A bare block can also define an anonymous subroutine, but it can't define a formal parameter list on the sub and can't define a named sub:

 $make_tea = {      my $tea = boil 'tealeaves';     combine $tea, 'sugar', 'milk'; } 

You can't use the return statement within an arrow sub or bare block sub to return from an anonymous sub. Blocks and arrow subs are commonly used for ordinary control flow, so return ignores them and only returns from subroutines defined with sub keyword or methods .



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net