Problems? Is your data what you think it is? | |
PerlMonks |
Re: Why use warnings? -wby dsheroh (Monsignor) |
on Feb 22, 2018 at 09:22 UTC ( [id://1209728]=note: print w/replies, xml ) | Need Help?? |
Why do I use strict and warnings 99+% of the time? Because, when (not if!) I need to debug my code, they are my absolute best friends in the world. When I make an error in my code, strict tells me about it before the program even starts running! When I go to track down a strange, usually data-dependent, behavior, warnings finds anomalies and points me to a good starting point for identifying their causes. And all of this help comes at essentially no cost.
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. 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.
In Section
Seekers of Perl Wisdom
|
|