在分配Perl 6程序之前使用Perl 6程序中的变量

Eug*_*sky 4 perl6

我想用我的程序将文字分配给文件末尾的一些变量,但是要先使用这些变量.我想出来的唯一方法是:

my $text;

say $text;

BEGIN {    
    $text = "abc";
}
Run Code Online (Sandbox Code Playgroud)

是否有更好/更惯用的方式?

Chr*_*oms 5

只是去功能.

改为创建子程序:

say text();

sub text { "abc" }
Run Code Online (Sandbox Code Playgroud)

更新(谢谢raiph!收集您的反馈,包括使用参考term:<>):

在上面的代码中,我最初省略了调用的括号text,但是为了防止解析器误解我们的意图,总是包含它们会更加可维护.例如,

say text();          # "abc" 
say text() ~ text(); # "abcabc"
say text;            # "abc", interpreted as: say text()
say text ~ text;     # ERROR, interpreted as: say text(~text())

sub text { "abc" };
Run Code Online (Sandbox Code Playgroud)

为避免这种情况,您可以创建text一个术语,这有效地使裸字的text行为与以下内容相同text():

say text;        # "abc",    interpreted as: say text() 
say text ~ text; # "abcabc", interpreted as: say text() ~ text()

sub term:<text> { "abc" };
Run Code Online (Sandbox Code Playgroud)

对于编译时优化和警告,我们也可以添加它的pure特性(感谢Brad Gilbert!).is pure声明对于给定的输入,函数"总是产生相同的输出而没有任何额外的副作用":

say text;        # "abc",    interpreted as: say text() 
say text ~ text; # "abcabc", interpreted as: say text() ~ text()

sub term:<text> is pure { "abc" };
Run Code Online (Sandbox Code Playgroud)

  • 请注意,Christopher声明的标识符(`text`)被声明为普通的`sub`.所以,例如,如果你写了"say text~text"你就不会显示`abcabc`,而是会得到一个运行时错误`过多的位置传递; 期望0参数,但得到1`因为第一个`text`将是一个`sub`,它传递`~text`作为参数. (2认同)
  • (继我之前的评论,cf [`term:<>`](https://docs.perl6.org/routine/term:%3C%3E#%28Syntax%29_term_term:%3C%3E),特别是`骰子`例子.) (2认同)
  • 您可能希望将`is pure`添加到`term:<text>`,以便可以发生编译时优化和错误. (2认同)