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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access