Its seldom a 'flaw in the code' if you need to check whether something has been defined. It could be a flaw from, say, user supplied input and your code needs to differentiate between data that was missing entirely (undef) and an empty string or 0.
You can't rely on warnings to tell you var didn't exist in the file, and you have no control over whether var gets defined.while (<FILE1>) { $var = GetVar($_); }; if ($var eq undef) { die "File provided doesn't include var!\n"; }
Also, there are benefits to "define when needed" if you have a complex set of processing which may or may not require a particular variable in numerous places and its impossible to predict which loop is going to need the variable first, if at all. Rather than needlessly calculating it before starting, just check for undef wherever you use it.
There are countless legitimate reasons why you'd want to check whether a variable has been defined, and its not a rare occurrence.
BTW, your second version is needlessly convoluted and will generate a warning (two if $var is undefined). KISS
That's the point of my example; the fact that it throws a warning (or two), and its not needlessly convoluted (although the opinion of convolutedness apparently varies). In fact, it provides more symmetry if your doing something like
if ($var eq undef) { ... } elsif ($var eq '') { ... } elsif ($var eq 'foo') { ... };
In reply to Re^3: Breaking The Rules
by Unanimous Monk
in thread Breaking The Rules
by Limbic~Region
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |