I have a condition:
next if ( ! ($x or $y or $z) );
The logic of the check is that at least one must be numerically non-zero to continue in the loop.
I trust that they actually are numbers.
The problem is that perl stores floats as strings internally. So a check on ! $x
where $x='0.00'
does not actually evaluate to true: my $x = 0.00;
if ( ! $x ) { never_gets_here(); }
What is the easiest way to force numeric evaluation of a variable without making the line too verbose?
I'm not sure where you get the idea that Perl stores floats as strings. Floats and strings are different things:
perl -le 'print 1 if 0.00'
perl -le 'print 2 if "0.00"'
2
If you want to force numeric context on an unknown scalar, you can just add zero to it, e.g.
unless ( $x + 0 ) { ... }
If you want to check whether a number is numerically non-zero, there is an operator for that:
next if (! ($x != 0 or $y != 0 or $z != 0) )
$x bool $x $x != 0
-------- -------- ----------------------------
0 false false
'0.00' true false
'0E0' true false
'string' true false, generates 'non-numeric' warning
'' false false, generates 'non-numeric' warning
undef false false, generates 'non-numeric' warning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With