如何在 Perl 中使用“ my”关键字?

我一直在线看到例如 Perl 脚本中变量名前面的 my关键字,但是我不知道它的意思。我尝试在网上阅读手册页面和其他网站,但我很难辨别它的用途,因为我看到它的使用方式和手册有所不同。

例如,在这篇文章中,它被用来获取数组的长度: 在 Perl 中查找数组的大小

但手册上说:

my声明列出的变量是 封闭的块、文件或 eval。如果列出了一个以上的值,则 列表必须放在括号内。

它是做什么的,如何使用的?

93687 次浏览

Quick summary: my creates a new variable, local temporarily amends the value of a variable

In the example below, $::a refers to $a in the 'global' namespace.

$a = 3.14159;
{
my $a = 3;
print "In block, \$a = $a\n";
print "In block, \$::a = $::a\n";
}
print "Outside block, \$a = $a\n";
print "Outside block, \$::a = $::a\n";


# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

ie, local temporarily changes the value of the variable, but only within the scope it exists in.

Source: http://www.perlmonks.org/?node_id=94007

Update

About difference between our and my please see

(Thanks to ThisSuitIsBlackNot).

Private Variables via my() is the primary documentation for my.

In the array size example you mention, it's not used to find the size of the array. It's used to create a new variable to hold the size of the array.

my restricts the scope of a variable. The scope of a variable is where it can be seen. Reducing a variable's scope to where the variable is needed is a fundamental aspect of good programming. It makes the code more readable and less error-prone, and results in a slew of derived benefits.

If you don't declare a variable using my, a global variable will be created instead. This is to be avoided. Using use strict; tells Perl you want to be prevented from implicitly creating global variables, which is why you should always use use strict; (and use warnings;) in your programs.


Related reading: Why use ABC0 and use warnings;?