Writing Safe Code

Declare your variables with my

Definitions

The my operator declares a variable or a list of variables to be local (private) to the enclosed block, subroutine or file. (Recall Example 1 and Example 3 from the Functions chapter.)

The region in which the private variable is recognized is called its scope. Variables declared with my are thus called lexically scoped variables.

A private variable will be recognized until the end of the innermost enclosing block, function or file. It will also be recognized in blocks contained within this region. However, a private variable of a function will not be recognized in another function called from that function (if you wish that it will, declare the variable with "local").

Lexical (private) variables will not exist and will not be recognized outside their scope.

The advantages of using my

It is recommended that you get used to declare all your variables with my.

By explicitly declaring the scope of each of your variables with my, you decrease the chance that variables from different parts of your program will accidentally have the same name and thus "step on each other". The usage of my is also important in cases that your code will be used as a modular part in other programs, whose variable names are unknown to you.

Example declarations

my $a;
my ($a, $b, $c); #the parentheses are obligatory
my @months;
my %students;    #a hash variable, about which we will learn later
my (@months, %students);
In these examples, the variables declared with my were initialized with the undef value.

You may initialize your lexical variables with other values, as in the following examples:

my $y = 2000;
my @months = ("Jan", "Feb", "Apr");
my ($a, $b, $c) = @months; #the parentheses are obligatory
my $text = $a . " " . $y;  #some operation
Note: If a list of variables is declared with my, the list must be enclosed in parentheses. If only one variable is declared with my, do not use parentheses (this might cause problems in statements like my ($line) = <FILEHANDLE>;, which we will learn later).

Further reading

Read more about my in the Perl documentation.


Table of Contents.
Next.