How should I use the “my” keyword in Perl?

痞子三分冷 提交于 2019-11-27 11:16:29
ikegami

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 use strict; and use warnings;?

Igor Chubin

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!