You want to declare all your variables with my. Scoping issues are one of the biggest causes of hard to find bugs.
Get into the habit of declaring your variables at the smallest scope possible. See Running a subroutine a certain number of times for a good example of scoping errors caused by not declaring variables. Get in the habit of using lexical (my'ed) variables whenever possible.
For the few global variables that you do need you and use the our keyword to make a package global variable. See chapter 4 of the Camel book for more information
If you find yourself needing to maintain a lot of state information throughout your program you might want to consider using and OO approach. See Damian Conway's "Object Oriented Perl" for a good introduction.
Trust me, scoping seems like an unneccessary pain-in-the-ass now, but soon you will be doing it as second nature (and preaching about it to others).
-pete
"Pain heals. Chicks dig scars. Glory lasts forever." | [reply] |
I have found that rather than "use warnings"
you may wish to just use the -w in the command line when testing your script.
It seems to become more of an acceptable option
when first starting out and you are still muddling
through the process.
I sometimes get so many warnings (I didn't say I was good)
that I can't see the output through the forest.!
"A body at rest, is an unstoppable force!"
| [reply] |
Put simply, global variables (without a very good reason) are a 'bad idea'.
Using my outside of a block or sub means that their scope is restricted to the file they are in. This should be wide enough scope for almost any purpose, and will allow you to share the var between subs declared in the same file without needing to pass them as parameters.
However, sharing vars between subs without passing them as parameters is also indicative of bad design (in most cases) as it makes it very difficult for the maintainance programmer coming along later to work out what sub is doing what with each variable.
Discussion on why globals are generally a bad idea is a big subject that would take considerable effort to put over if you are not already aware of the reasons.
| [reply] |
You can also declare your variables with "our". That way they aren't restricted to the subroutine or block. | [reply] |
Well, they are. Sort of.
our creates an alias to a package variable.
That is, our $foo is an alias to
$PACKAGE::foo, where PACKAGE
is your current package. The package variable will always
exist, but the alias is lexically scoped.
use strict;
$main::foo = 1;
{
our $foo;
print $foo, "\n";
}
# print $foo, "\n";
print $main::foo, "\n";
This prints 1\n1\n. But if you remove the
#, the code doesn't compile.
Abigail | [reply] [d/l] [select] |