5.11 Macros

     

Macros are a powerful way of manipulating source code at compile time. Macros must be declared before they're called. A call to a macro routine executes as soon as it's parsed. The parser substitutes the return value from the macro into the parse tree in place of the macro call. If a macro returns undef , it makes no entry in the parse tree. So, the macro disappear takes a single string argument and returns undef . Any call to disappear is replaced at compile time with nothing, just as if it were commented out.

 macro disappear (Str $thinair) {     return; }  . . .  disappear("Some text you'll never see"); 

If a macro returns a string, the string is parsed as Perl source code, and the resulting parse tree replaces the macro call. So, anywhere the macro twice is called, it is replaced at compile time by a for modifier:

 macro twice {     return "for 1..2"; }  . . .  print "\n" twice;     # same as:  print "\n" for 1..2; 

If a macro returns a block, that block is parsed as a closure, and the resulting parse tree replaces the macro call. So, when the reverse_numeric macro is called, the parser substitutes the block { $^b <=> $^a } in place of the call:

 macro reverse_numeric {     return { $^b <=> $^a }; }  . . .  sort reverse_numeric, @values; 

If a macro returns a parse tree, the parser substitutes it directly for the macro call. The returned tree may be the original parse tree, a modified parse tree, or a manufactured parse tree.

By default, a call to a macro is parsed just like an ordinary subroutine call, so it can take no arguments or a comma-separated list of arguments. But, macros can also modify the way their arguments are parsed, by adding an is parsed trait. The trait takes a rule as an argument, and will parse whatever code follows using that rule instead of the normal rule for parsing subroutine arguments. So, the macro funky essentially translates a "ValSpeak" subroutine call into an ordinary Perl subroutine call. It takes a single string argument, which it parses as a sequence of word-forming characters , surrounded by the strings "like" and ", you know". (For more on rules, see Chapter 7.) It then returns a block that will call the plain subroutine with the single argument passed to funky .

 macro funky (Str $whatever)     is parsed (/:w like (\w+), you know/)    {    return { plain($whatever); };   }    . . .    funky like whatever, you know 



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