|There's more than one way to do things|
Re: Use Strictby dvergin (Monsignor)
|on Jul 17, 2003 at 02:50 UTC||Need Help??|
I'll take a shot at the "why" part with an example.
Can you spot the error in the following snippet adapted from your code example?
If you look carefully you will see the flaw. But chances are strong that you would not notice it if you were staring at a whole page of code instead of just three lines. I've missed things much more obvious than this countless times.
'use strict' would find this error immediately and tell you exactly were it was.
Granted, a slip of the finger is not likely to produce this specific error. But many, many times I have had strict catch things I had looked at several times and missed. Once you become used to coding for strictness, you will find it an indespensable aid to accuracy in coding.
The problem with not using strict is that usually the code will run but it will behave strangely and you will have little clue where to start looking for the problem.
Think of strict as a way to say to Perl: "This is the name I intend to use for this variable. If I accidently spell it any other way, point out the exact line where I blundered."
You may feel that strict is too much bother in short programs. My advice: use it in short programs anyway until it becomes second nature. That way when you are writing longer programs, you won't hit a sudden learning curve.
Update: Another way strict-compliant coding often helps me can be illustrated by this snippet:
Scoping: when I see that "my $value" inside the brackets of the 'if' block I know immediately that the $value has not been messed with before this 'if' block. I also know that it is not doing any mischief after this block. It is only present inside this block. That is an enormous benefit in figuring out what code (even your own) is doing.
It can be a real frustration to be debugging or editing code and have no visual clue as to the scope of a variable. Can I safely mess with this variable? Did it have a value before we got here? Is something happening with it after this block that I need to be aware of? Who knows? ...unless the writer used strict and keep variable scope as narrow as possible.