in reply to To warn or not to warn, that is the question
I'll echo several people and say that undef is not 0 and if there is no difference between the function returning 0 and it returning undef, then the function needs to be fixed to stop returning useless undefs. If there is a difference, then you need to not only tell Perl but tell whoever will next maintain your code that you consciously want to treat undef as if it were 0 because in this specific case that makes sense.
And trying to optimize 0.5% out of one tiny part of your code (so that your total CPU savings are more like 0.005%) at the cost of less clear code is madness.
But, I do feel your pain when it comes to dealing with undefined values without generating warnings. This is such a common problem that over and over again someone proposes an alternate form of ||, call it ||| this time, that works on undefinedness instead of falseness. That way you can write:
ormy $x= some_sub() ||| 0;
Now in this case, || and ||= actually work just fine. But if you wanted to treat undef as -1, for example, then || would also treat 0 as -1 (probably not what you want). This has been spinning around in my head for some time and def -- Deal nicely with undefined values is what has finally popped out. You'd use it like:my $x= some_sub(); $x |||= 0;
ormy $x= def( some_sub(), -1 );
With no second argument, it defaults to "", which is what I find I want the most often. In a void context it actually modifies its first argument. If you pass in a true value as a third argument, then def() modifies its first argument even if def() isn't used in a void context. - tye (but my friends call me "Tye")my $x= some_sub(); def( $x, -1 );
|
|---|