#!/usr/bin,/perl -w
$x = "MAIN"; # in default package, "main"
package Foo;
$x = 123; # in package "Foo", so this is $Foo::x
package Bar;
$x = 456; # in package "Bar", so this is $Bar::x
package main; # back to normal
print "\$$x = '$x'\n";
print "\$main::$x = '$main::x'\n";
print "\$Foo::$x = '$Foo::x'\n";
print "\$Bar::$x = '$Bar::x'\n";
This prints:
$MAIN = 'MAIN'
$main::MAIN = 'MAIN'
$Foo::MAIN = '123'
$Bar::MAIN = '456'
In summary: it's a way to have global variables of the same name which nevertheless don't trample on each other. That way you don't have to worry if you happen to use the same name for a variable as used in some obscure module.
Commonly modules have their own package, and the standard convention is that it's the same as the module name. use relies entirely on that convention for it's import mechanism — which is a way to make variables and subs visible unqualified across package boundaries, by making aliases to the same variables in the different packages. Thus, if you import $Foo::x into Bar, then $Bar::x will point to the same variable as $Foo::x does. Any modification of one will be reflected in a change in the other. You're probably familiar with that effect, but you likely didn't realise how simple the underlying implementation really is. Because it is.
|