I keep seeing the "my" keyword in front of variable names in example Perl scripts online but I have no idea what it means. I tried reading the manual pages and other sites online but I'm having difficulty discerning what it is for given the difference between how I see it used and the manual.
For example, its used to get the length of the array in this post: Find size of an array in Perl
But the manual says:
A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses.
What does it do and how is it used?
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. Usinguse strict;
tells Perl you want to be prevented from implicitly creating global variables, which is why you should always useuse strict;
(anduse warnings;
) in your programs.Related reading: Why use
use strict;
anduse warnings;
?Quick summary:
my
creates a new variable,local
temporarily amends the value of a variableIn the example below, $::a refers to $a in the 'global' namespace.
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
andmy
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.