Perl-Sensitive Sunglasses | |
PerlMonks |
Should "use strict" complain if I use a variable that is not declared?by earthman (Initiate) |
on Jun 28, 2010 at 08:06 UTC ( [id://846831]=perlquestion: print w/replies, xml ) | Need Help?? |
earthman has asked for the wisdom of the Perl Monks concerning the following question: When designing a class, I have developed the habit of allowing the constructor to take, in the arguments passed to the new() method, extra properties with which to prepopulate the object . This looks something like:
Recently, I discovered that there is a major problem with the preceding method. The problem is that the condition prevents the "my" if the condition is false and, furthermore, strict does not complain that the "my" failed (or may fail) to occur. If the conditional prevents %self from being declared, using %self results in unexpected behavior that I depended upon "use strict" to prevent. The following small code example illustrates the problem:
The output on my machine looks like:
What is notable about the output is that the addresses of the hash references returned from testref1 refer to the same hash, while testref2 returns references to two different hashes. This can be further seen by assigning data to the $a hashref and printing this data using the $b hashref. The result, in my production code, is that the new() method of my classes returns the same object over and over, when I would have preferred to have gotten a new() one. I have no problem separating the variable declarations from any conditions wherever it occurs in my code, but I expected strict to warn me about a failure to declare a variable. When I got no messages from strict, I assumed (incorrectly) that the declaration was exempt from the condition. Should strict complain about a conditional declaration? Thanks! Michael Krebs
Back to
Seekers of Perl Wisdom
|
|