Getting Started
Introduction
Perl IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Top Sites
More Tutorials
Books
Magazines
Articles
NewsLetters
Mailing Lists
NewsGroups
Forums
User Groups
Talk Shows
Blogs
Clothing

GBIC >> Perl >> Information Center Tutorials >> Scope

Perl Information Center Tutorials - Scope
These tutorials were written to help you get a quick, but thorough, understanding of Perl - the scope of the language as well as it's specific capabilities.

Beginners Built-In Functions     Advanced CGI Applications

Global Scope
By default, when a variable is created by assigning it a value, the variable is available everywhere in the program, including within subroutines. This is called a global scope. The following code gives an example.

     $x = 5        # $x is available anywhere in the program
     sub mytest {  # subroutine 'mytest'
        print $x;  # $x is global, so '5' is printed
     }

Controlling Scope
However, by using the 'my' operator when creating a variable, the variable's scope will be limited to the block in which the variable was created, as in the following example:

     { $x=5;     # $x is global, existing in all blocks
       my $y=6}  # use of 'my' means $y exists only in this block
     print $x;   # $x is global '5' is printed
     print $y;   # this is outside the block, so $y is empty

Variables created using 'my' are said to be lexically scoped variables.

The use of 'my' is considered a best practice because it helps avoid the problem where programmers accidentally reuse variable names throughout a program, causing the variables to take on unexpected values.

Subroutines
Variables defined in subroutines are also global and may be accessed from within the main program, unless declared using 'my' as in the following example.

     $x=5;         # $x is global, existing in all blocks
     sub mytest {  # subroutine 'mytest'
        print $x;  # $x is global, so '5' is printed
        $y=5;      # global - accessible outside 'mytest'
        my $z=5;   # local - not accessible outside 'mytest'
     }
     &mytest;      # call 'mytest' 
     print $y;     # $y is global, so '5' is printed
     print $z;     # $z is not global, so nothing is printed