Scoping Revisited

 <  Day Day Up  >  

In Hour 5, "Working with Files," you learned about variables and variable scope. Specifically you learned that the my keyword declares that a variable is local only to the program, or to any curly braces that might be around it. Look at the example in Listing 17.3.

Listing 17.3. Small Scoping Example
 1:  #!/usr/bin/perl w 2: 3:  use strict; 4:  my $max = 15; 5: 6:  sub read_max { 7:      my $counter = 0; 8: 9:      while(<DATA>) { 10:         my $line = $_; 11:         if ($counter++ < $max) { 12:             print $line 13:         } 14:     } 15: } 16: read_max(); 

The variable $max is visible anywhere within the program, $counter is visible only within the subroutine, and $line is visible only within the while loop.

In Hour 5, I said that with strict in place you had to declare all variables with the my declaration. That was misleading. The strict compiler directive will also allow you to use variables not declared with my as long as you use the fully qualified package name shown in Listing 17.4.

Listing 17.4. Small Program Using Package and Lexical Variables
 1:  #!/usr/bin/perl w 2: 3:  use strict; 4:  $main::max = 15; 5: 6:  sub read_max { 7:      my $counter = 0; 8: 9:      while(<DATA>) { 10:         my $line = $_; 11:         if ($counter++ < $main::max) { 12:             print $line 13:         } 14:     } 15: } 16: read_max(); 

Notice that $main::max isn't declared with my anywhere. This program will compile and run without errors because $max was only used by its fully qualified package name. These variables are called package variables , whereas the variables declared with my are called lexical variables .

This becomes important when your program is spread over two or more files. If every variable were declared with my , there would be no way to directly affect variables in other modules. (Some programming languages might consider this a good thing, but Perl thinks this is too restrictive .)

By the Way

In Hour 14, "Using Modules," in Listing 14.1 you saw the File::Find module use these kinds of variables. In that example, you changed the variable $File::Find::name which contained the name of the file that was currently being examined.


 <  Day Day Up  >  


SAMS Teach Yourself Perl in 24 Hours
Sams Teach Yourself Perl in 24 Hours (3rd Edition)
ISBN: 0672327937
EAN: 2147483647
Year: 2005
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net