问题描述
此代码使用(实验性)宏:
This code that uses (experimental) macros:
use experimental :macros;
macro new-var() {
quasi {
my $a = 42
}
};
new-var;
say $a
通过Variable '$a' is not declared
失败,尽管宏通过时没有错误.如果那是正确的宏声明,那该怎么办?如果不是,是否有办法从宏中定义新变量?
Fails with Variable '$a' is not declared
, although the macro passes through without an error. If that's a correct macro declaration, what does it do? If it's not, is there a way to define new variables from within a macro?
推荐答案
moritz的回答关于宏的状态是正确的,尽管从我对007中所做工作的了解来看,我不认为该程序是即使在Perl 6宏的有效实现下,编写的文本也是正确的.
The answer from moritz is correct about the state of macros, though from what I know of the work being done in 007, I don't think the program as written would be correct even with a working implementation of Perl 6 macros.
Perl 6宏本质上不是文本的(C宏是文本的示例). quasi
是一个引号结构,与我们对字符串和正则表达式的引号非常相似,不同之处在于它引用了Perl 6代码,并将其表示为AST-ish. (我曾经说过它会产生AST,但已经意识到,如果要在准内部插入一个中缀,则它具有优先级和关联性,我们实际上不能为该类形成正确的树.表达式直到插值之后.)
Perl 6 macros will not be textual in nature (C macros are an example of textual ones). A quasi
is a quote construct, much like we have quotes for strings and regexes, except that it quotes Perl 6 code, representing it as something AST-ish. (I once would have said that it produces AST, but it's been realized that if an infix were to be interpolated inside of a quasi, then it comes with a precedence and associativity, and we we can't actually form the correct tree for the expression until after interpolation.)
有一个卫生"的宏概念,在宏主体中声明的符号默认情况下不应泄漏到应用宏的位置,因为它们很可能只是实现细节.必须明确要求将符号放入应用宏的编译上下文中.因此,我希望程序必须如下所示:
There's a macro concept of "hygiene", whereby symbols declared in the macro body should not, by default, leak out to the place that the macro is applied, since they may well just be implementation details. One would have to explicitly ask to put a symbol into the compiling context where the macro is applied. So I expect the program would have to look like this:
macro new-var() {
quasi {
my COMPILING::<$a> = 42
}
};
new-var;
say $a
请注意,尽管您可能会发现类似的东西可以在007中使用,但今天在Rakudo中将无法使用.
Note that this won't work today in Rakudo, although you might find something like it can be made to work in 007.
这篇关于宏不允许定义词法变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!