|We don't bite newbies here... much|
Re: How to localize conditionally?by ELISHEVA (Prior)
|on Mar 14, 2011 at 05:13 UTC ( #893027=note: print w/replies, xml )||Need Help??|
Personally, I'd go with JavaFan's solution if you only have one environment variable and autovivification "risk" is not a concern to you (see replies to JavaFan's response above). I like the way it keeps the impact of the condition clearly focused on the variable and also makes clear the possible values.
Although this code
is overkill for a single state variable, you might want to consider it later on, if it turns out that you have to set up multiple state all tied to the same condition. Were you to avoid the "if", and repeat the condition for each environment variable you need to set, you might well have a code duplication problem.
On the other hand, I'd be hard pressed to call a single statement containing a parameterless subroutine call "code duplication". Code duplication (don't repeat yourself) typically applies to expressions with "movable parts": a single call with a long parameter list, multiple expressions passed as parameters, a conditional assignments ($x= COND ? A : B)or multiple lines of code. In these cases replication is problematic because multiple expressions and statements with identical internal logical are repeated. If the internal logic in one is buggy, all will be buggy and need to be fixed.
However, a single parameterless function call has no internal moving parts. There are no "debug everywhere issues". Either you named the function correctly in a particular location or you didn't and that is about the limit of the debugging effort.
Update: added comment about autovivification risk.
In Section Seekers of Perl Wisdom