in reply to Top level my vars and their global use in a file
It is not a faux pas to access my variables globally, it's impossible (well, kind of). Global variables are attached to a namespace and that is how other packages access them. my variables are limited to the scope they are declared in.
Often, I'll establish my database connection that the beginning of a package and allow all subs in that package to use the lexically scoped DBI object. This works well if I have many places that use it.
Global variables tend to be more dangerous if they are shared between packages. This makes the packages interdependant. If you need to change a global in one package, you need to search through all other packages that reference this global variable and update them. This is a Bad Thing.
Of course, this also occurs when you have a my $var at the top of a particular package. If you have a bunch of subs that use it and you need to change the name, this could be problematic, but generally much less of an issue than if you're using a global across different packages.
Terminology alert: my variables declared in a package can only be accessed in that package. They are not globals and can only be accessed in the scope in which they were declared. Try the following (strict deliberately not used):
use Data::Dumper; $x = 1; print Dumper( \%:: );
By examining the output, you'll see that $x is in the main namespace. However, by putting a my in front of $x, it's removed from the namespace.
One thing I am unclear on, though: what mechanism does Perl use to access those variables that are lexically scoped and not in a namespace?
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (Ovid) Re: Top level
by petral (Curate) on May 24, 2001 at 00:02 UTC | |
by Ovid (Cardinal) on May 24, 2001 at 00:07 UTC |