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, ...

Get Perl 6 and Parrot Essentials, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.