in reply to Re: Understanding variable scope in perl
in thread Understanding variable scope in perl

Thanks for your replys guys. Is it always a good idea to use 'my'? Also, what does use 'strict' allow you to do?
  • Comment on Re^2: Understanding variable scope in perl

Replies are listed 'Best First'.
Re^3: Understanding variable scope in perl
by kwaping (Priest) on Sep 29, 2005 at 19:09 UTC
    This is a good node that will answer both of your questions. Use strict and warnings

    Here are my own takes on these subjects:

    Using "my" is generally a good idea. It sets the scope of the variable it's applied to to be localized instead of global. I'm sure others here can provide a much more detailed explanation of it. Basically, my recommendation is to use it whenever possible, except in times when you explicitly do not want to use it for a very good reason. "You have to know the rules in order to break them", that kind of thing.

    Regarding "strict", that's also a good thing to use whenever possible. Just like "my", only turn it off when you have a good reason to and you know exactly what you're doing. Strict forces you to write "better" code, in the sense of barewords, subs, variable scoping and the like. One of the things "strict" does is it forces you to scope all your variables using "my", "local", "our", or the package name.
Re^3: Understanding variable scope in perl
by liverpole (Monsignor) on Sep 29, 2005 at 19:02 UTC
    For an answer about what "strict" does, see the output of perldoc strict.

    Yes, I would say it's *almost* always a good idea to use "my".  It causes your variables to be lexically-scoped rather than globally-scoped, which can avoid many unintended bugs, and is considered an important programming practice.  (It's also one of the principles of object-oriented programming).

    If you get into the habit of using it religiously, along with "strict" and "warnings", you'll avoid many pitfalls on your path to Perl enlightenment.  I was lucky enough to be steered onto the path of using the "-w" switch, (eg. perl -w), from almost the first time I started using Perl (the -w switch has the same effect as "warnings", which go hand-in-hand with "strict"), and it's saved me from countless headaches!