Perl Programming Understanding Scope and Packages in Perl |
Understanding Scope It’s now time to have a look at what we’re doing when we declare a variable with my(). The truth, as we’ve briefly glimpsed it, is that Perl has two types of variable. One type is the global variable (or package variable), which can be accessed anywhere in the program, and the second type is the lexical variable (or local variable), which we declare withmy(). Global Variables All variables in the program are global by default. Consider this code: #!/usr/bin/perl -w $x = 10; $xis a global variable. It is available in every subroutine in the program. For instance, here is a program that accesses a global variable: #!/usr/bin/perl -w $x = 10; access_global(); sub access_global { Executing this code shows that$xis accessible inaccess_global(): $ perl global1.pl Since variables within functions are global by default, functions can modify variables as shown in this program: #!/usr/bin/perl -w $x = 10; print "before: $x\n"; sub change_global { This program assigns the global variable$xthe value 10 and then prints that value. Then,change_global()is invoked. It assigns$xthe value 20—this accesses the global variable$x—and then prints its value. Then in the main part of the code, after the function is called, the global$xis printed with its new value—20. Here we see the proof: $ perl global2.pl The fact that Perl function variables are global by default is itself not a bad thing, unless of course you are not expecting it. If you are not expecting it, then accidentally overwriting global variables can cause hard-to-find bugs. If you are expecting it, you will probably want to make function arguments local.
blog comments powered by Disqus |
|
|
|
|
|
|
|