当 my() 有条件时会发生什么? [英] What is happening when my() is conditional?

查看:58
本文介绍了当 my() 有条件时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 perl -w -Mstrict 进行比较:

# case Alpha
print $c;

...

# case Bravo
if (0) {
  my $c = 1;
}

print $c;

...

# case Charlie
my $c = 1 if 0;
print $c;

AlphaBravo 都抱怨全局符号没有明确的包名称,这是意料之中的.但是 Charlie 没有给出同样的警告,只是该值未初始化,闻起来很像:

Alpha and Bravo both complain about the global symbol not having an explicit package name, which is to be expected. But Charlie does not give the same warning, only that the value is uninitialized, which smells a lot like:

# case Delta
my $c;
print $c;

幕后到底发生了什么?(即使永远不应该为生产代码编写这样的东西)

What exactly is going on under the hood? (Even though something like this should never be written for production code)

推荐答案

您可以将 my 声明视为在编译时和运行时具有操作.在编译时,my 声明告诉编译器注意一个符号存在并且在当前词法作用域结束之前一直可用.该声明中符号的赋值或其他使用将在运行时进行.

You can think of a my declaration as having an action at compile-time and at run-time. At compile-time, a my declaration tells the compiler to make a note that a symbol exists and will be available until the end of the current lexical scope. An assignment or other use of the symbol in that declaration will take place at run-time.

所以你的例子

my $c = 1 if 0;

就像

my $c;         # compile-time declaration, initialized to undef
$c = 1 if 0;   # runtime -- as written has no effect

<小时>

请注意,这种编译时/运行时的区别允许您编写这样的代码.


Note that this compile-time/run-time distinction allows you to write code like this.

my $DEBUG;    # lexical scope variable declared at compile-time
BEGIN {
    $DEBUG = $ENV{MY_DEBUG};   # statement executed at compile-time
};

现在你能猜出这个程序的输出是什么吗?

Now can you guess what the output of this program is?

my $c = 3;
BEGIN {
    print "\$c is $c\n";
    $c = 4;
}
print "\$c is $c\n";

这篇关于当 my() 有条件时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆