简体   繁体   English

BEGIN块中的变量声明

[英]Variable declaration in BEGIN block

In a script like the following, is it possible without dropping 'my' to effectively declare 'var' only once and have it visible outside the BEGIN block? 在如下的脚本中,是否可以在不删除'my'的情况下有效地仅仅声明'var'一次并使其在BEGIN块之外可见?

echo -e "\n\n\n" | \
  perl -lne 'BEGIN { my $var="declared & initialized once" } print $var'

Also, why declaring var without 'my' makes it visible outside the BEGIN block? 另外,为什么在没有'my'的情况下声明var会使它在BEGIN块之外可见?

Place a my $var; 放一个my $var; before the BEGIN block: BEGIN块之前:

$ perl -le 'my $var; BEGIN { $var = "declared"; } print $var;'
declared

my gives the variable lexical scope, so $var is not defined in your example outside the BEGIN block. my给出了变量词法范围,因此在BEGIN块之外的示例中没有定义$var Removing the my effectively makes it a global variable, which is accessible across the script after assignment. 有效地删除my使其成为一个全局变量,可以在赋值后通过脚本访问它。

Also, why declaring var without 'my' makes it visible outside the BEGIN block? 另外,为什么在没有'my'的情况下声明var会使它在BEGIN块之外可见?

You're not declaring it then. 那时你还没有宣布。 It is autodeclared as global, if you're not using use strict (which prevents the declaration by default). 如果您没有使用use strict (默认情况下会阻止声明),它会自动声明为全局声明。 In a one-liner, strict hurts more than it helps; 在单行中, strict伤害超过它的帮助; I'm perfectly fine with not doing a declaration in such a context. 我完全没有在这样的背景下做声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM