|Don't ask to ask, just ask|
The main trouble is that the content of the variable is unprotected. Nothing is stopping any code anywhere from setting it to whatever it likes. It may not be malicious: it just might be that someone has a variable with a proximate name, and by a slip of the keyboard they type the name of the global variable inadvertently).
If unexpected changes are occurring to it, you will want to find where it is being changed. You will have little choice but to step through the code line by line in the debugger to find the offending code. This can be tedious.
When you sit down and think about a global variable, in nearly all cases, all you want to do is to set it once, and from then on, refer to it ever after. In that case, the following snippet will get you on your way:
If you want to get paranoid, it would easy to extend the above to allow you to set the value one time only, (e.g., test if the contents are undefined) and any subsequent calls to set_var are silently ignored.
Another frequent thing to do with a global variable is to be able to increment a variable (but not be able to set it to an arbitrary value), and to read the current value back:
In both cases, the $var variable is protected: you can't get at the variable directly to fiddle with it. You can't even define a new subroutine to get at it. All you have are the officially sanctioned routines to manipulate it.
And the really great thing with this approach is that if you have some errant code that is setting $var to some wacky value, or incrementing it when you don't expect it, all you have to do is to hang a breakpoint off the name of the sub in the debugger, and then just let it run at full clip until the routine gets called. Much less tedious.
Oh, and I wouldn't call these routines var, I'd use a more descriptive name.
- another intruder with the mooring of the heat of the Perl
In reply to Re: Global variable vs passing variable from sub to sub