Home
Search Perl pages
Subjects
By activity
Professions, Sciences, Humanities, Business, ...
User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...
Text Strings
Conversions, tests, processing, manipulation,...
Math
Integer, Floating point, Matrix, Statistics, Boolean, ...
Processing
Algorithms, Memory, Process control, Debugging, ...
Stored Data
Data storage, Integrity, Encryption, Compression, ...
Communications
Networks, protocols, Interprocess, Remote, Client Server, ...
Hard World Timing, Calendar and Clock, Audio, Video, Printer, Controls...
File System
Management, Filtering, File & Directory access, Viewers, ...
|
|
|
local($x) saves away the old value of the global variable $x, and assigns a new value for the duration of the subroutine, which is
visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping.
local() always affects global variables, also called package
variables or dynamic variables.
my($x) creates a new variable that is only visible in the current subroutine. This
is done at compile-time, so is called lexical or static scoping.
my() always affects private variables, also called lexical
variables or (improperly) static(ly scoped) variables.
For instance:
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
Notice how at no point does the value ``private'' get printed. That's
because $var only has that value within the block of the
lexical() function, and it is hidden from called subroutine.
In summary, local() doesn't make what you think of as private,
local variables. It gives a global variable a temporary value.
my() is what you're looking for if you want private variables.
See also the perlsub manpage, which explains this all in more detail.
Source: Perl FAQ: Perl Language Issues Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington. |
Next: How can I access a dynamic variable while a similarly named lexical is in scope?
Previous: How do I create a static variable?
(Corrections, notes, and links courtesy of RocketAware.com)
Up to: PERL
Rapid-Links:
Search | About | Comments | Submit Path: RocketAware > Perl >
perlfaq7/What_s_the_difference_between_dy.htm
RocketAware.com is a service of Mib Software Copyright 2000, Forrest J. Cavalier III. All Rights Reserved. We welcome submissions and comments
|