我想用我的程序将文字分配给文件末尾的一些变量,但是要先使用这些变量.我想出来的唯一方法是:
my $text;
say $text;
BEGIN {
$text = "abc";
}
Run Code Online (Sandbox Code Playgroud)
是否有更好/更惯用的方式?
只是去功能.
改为创建子程序:
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)