如何在Perl中自动初始化所​​有标量变量? [英] How can I automatically initialize all the scalar variables in Perl?

查看:96
本文介绍了如何在Perl中自动初始化所​​有标量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 默认情况下自动将变量初始化为undef.

Perl automatically initializes variables to undef by default.

是否有一种方法可以覆盖此默认行为,并告诉Perl解释器将变量初始化为zero(或其他一些固定值)?

Is there a way to override this default behavior and tell the Perl interpreter to initialize variables to zero (or some other fixed value)?

推荐答案

代码完整"中的建议对于诸如C之类的语言很重要,因为当您拥有

The recommendation in Code Complete is important for language such as C because when you have

int f(void) {
   int counter;
}

counter的值就是占用该内存的任何情况.

the value of counter is whatever happens to occupy that memory.

在Perl中,当您使用声明变量时

In Perl, when you declare a variable using

my $counter;

毫无疑问,$counter的值是undef而不是一些随机垃圾.

there is no doubt that the value of $counter is undef not some random garbage.

因此,Perl会自动满足该建议的动机,即确保所有变量均以已知值开头,并且无需执行任何操作.

Therefore, the motivation behind the recommendation, i.e. to ensure that all variables start out with known values, is automatically satisfied in Perl and it is not necessary to do anything.

对计数器的操作是增加或减少它们.结果:

What you do with counters is to increment or decrement them. The result of:

my $counter;
# ...
++ $counter;

在Perl中有很好的定义. $counter将保留值1.

is well defined in Perl. $counter will hold the value 1.

最后,我要指出的是,在大多数情况下,Perl中不需要计数器,因此可能需要重写大量使用计数器变量的代码.

Finally, I would argue that, in most cases, counters are not necessary in Perl and code making extensive use of counter variables may need to be rewritten.

这篇关于如何在Perl中自动初始化所​​有标量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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