in reply to Why use warnings? -w
As for why everyone always starts answers to "what's wrong with my program?"-type questions with an admonition to use strict and warnings, that's also because they're such important debugging tools. More often than not, if someone is asking a beginner-to-intermediate-level "what's wrong with my program?" question, all they have to do is turn on strict and warnings and Perl itself will tell them the answer to their question in less time than it takes to ask the internet for help.
But I do agree with you that the use of uninitialized value warnings can be a bit overzealous at times.
In JavaScript, anYes, if you declare a variable with my in Perl, the variable exists only within the scope where it is declared. (Most of us around here would say that it is "lexically scoped".) And this is generally a Very Good Thing. Global variables aren't inherently bad, per se, but well over 95%, probably over 99%, of the variables I use (outside of one-liners) are lexically scoped. I never use a global variable without a compelling reason to do so.uninitializedundeclared variable automatically becomes a global variable when we use it. So, if I refer to A in my function, then when I type "A = 5" it becomes a global variable. But if I initialize it as "var A = 5" then it becomes a temporary variable that exists only within the scope of that function. Is Perl treating variables the same way?
So why do people say you should avoid globals? Again, the answer is "easier debugging". A global variable exists everywhere throughout your entire program, which means that if you change it in one part, it can cause bugs in any other part, even if the change and the bug are in different source files or thousands of lines away from each other within the same file. Finding the cause of this kind of action-at-a-distance bug can be nearly impossible, but they happen very easily, requiring nothing more than thinking the same variable name is appropriate in two different places or even a simple typo to occur.
In contrast, if you habitually use lexical ("my") variables and restrict each of them to the smallest possible scope, then the variable lives and dies, usually, within a short enough section of code that you can have its entire lifespan on your screen at once. There's no chance of it being invisibly modified elsewhere, because it doesn't exist elsewhere. If the same variable name is referenced somewhere else? No problem! Since it's a different scope, that's a completely separate variable which just happens to have the same name, so they won't interfere with each other.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Why use warnings? -w
by mh88 (Novice) on Feb 28, 2018 at 21:18 UTC |