|XP is just a number|
RE (tilly) 3: redeclaring variables with 'my'by tilly (Archbishop)
|on Nov 10, 2000 at 22:40 UTC||Need Help??|
As davorg said, because it is a good software engineering practice.
Pick up a good book on programming (eg Code Complete) and read up on the concepts of loose coupling vs tight coupling. Tightly scoped variables go hand in hand with loose coupling between different sections of code which goes hand in hand with code that is easier to maintain, adapt, and modify.
These principles have been known for decades, but far too many people don't know about them. Also a lot of people have (sorry to pick on you) misconceptions such as beliefs that you need to make it easy to keep track of all variables you use anywhere.
That is actually the opposite of what you should want.
You want to make it absolutely useless to keep track of as many variables as possible by giving them private scopes where they cannot accidentally have anything non-obvious happen to them. Guaranteeing no accidents with a tight scope is safer and easier to maintain than manually remembering which variables got used somewhere and so should not be accidentally stomped on.
However when you are done there are a small list of variables that you will need to give larger scopes to. (For instance package globals that you are willing to export.) It is still a good style to put those at the top. But now you get a second win. By winnowing down the list of global variables to the minimum necessary, you have made the list of important things to remember much smaller. Therefore you have just made it easier to keep track of things that you needed to track!
So the recommended style then works out to at the top of your file use strict to catch mistakes, use vars to declare in an obvious place everything that you need to track in your code, and then protect every little variable you need to use by making them lexicals with tiny scopes. The protection from scoping then protects those far more securely than you could do manually, and you will find it easier to track and manually protect the few that are left over.
Given the choice when hiring a Perl programmer, I would prefer to hire someone who understood good software engineering principles but didn't know Perl than I would to hire someone who knew a lot of Perl but thought good software engineering was bunk. I am confident that I can teach the first person to program in Perl. I don't know how to keep the second from being a hazard to the company's code-base.