|No such thing as a small change|
Re: Setting Global Variable in Subby stephen (Priest)
|on Apr 30, 2002 at 16:17 UTC||Need Help??|
First I'll tell you why global variables are Bad; then I'll explain how to get yourself into trouble if you so choose.
Global variables are one of the most common sources of bugs in code. Worse, once they're in there, global variables are hard to stamp out, and the bugs they cause are difficult to trace. Here's an example:
The person that wrote this code expected the last line to print "Who am I? Jean ValJean, 24601!" Instead, we got "Who am I? THX, 1138!" And unfortunately, the bug is not easy to trace. Imagine if I had added flee_javair(), adopt_cosette(), etc., etc. The bug (which is in the if-statement for steal_candlesticks()) could be anywhere that $number is referenced... and there's no easy way to find it.
You may be wondering why one would make so much fuss over a small program. The first reason is that useful programs tend to grow over time. Since we always hope that we're writing useful programs, we should always be prepared to wake up one morning to discover that our small CGI program has become gigantic. The second reason is that global variables become a hard habit to break once you're used to them. It's always best to start good habits as soon as possible.
"So what do I do instead?" Glad you asked. The best way to get variables out of a subroutine is to return them from a subroutine. If you want to return two or three, you can simply return a list:
Finally, here's the part where I tell you how to completely disregard all that I've been saying. (Several people have no doubt done so while I've been typing. :) )The my keyword is used to declare local variables. In other words, they're only visible in the subroutine (or other block) you declared them in.
Note: Code is not tested, and I still can't hit the high tenor notes in Les Miz.
Update: Fixed typos, and for some reason I had the link to "our" labeled "my".