Section 10.9. Packages and Lexicals


10.9. Packages and Lexicals

A lexical variable (a variable introduced with my) isn't prefixed by the current package because package variables are always global: we can always reference a package variable if we know its full name. A lexical variable is usually temporary and accessible for only a portion of the program. If we declare a lexical variable, then using that name without a package prefix gets the lexical variable. A package prefix ensures that we are accessing a package variable and never a lexical variable.

For example, suppose a subroutine within navigation.pm declares a lexical @homeport variable. Any mention of @homeport will then be the newly introduced lexical variable, but a fully qualified mention of @Navigation::homeport accesses the package variable instead.

 package Navigation; @homeport = (21.283, -157.842); sub get_me_home {   my @homeport;   .. @homeport .. # refers to the lexical variable   .. @Navigation::homeport .. # refers to the package variable } .. @homeport .. # refers to the package variable 

Obviously, this can lead to confusing code, so we shouldn't introduce such duplication needlessly. The results are completely predictable, though.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

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