Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to treat number as numeric in perl?

Tags:

perl

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?

like image 280
Dale Forester Avatar asked Nov 16 '11 18:11

Dale Forester


2 Answers

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 ) { ... }
like image 53
friedo Avatar answered Nov 15 '22 00:11

friedo


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
like image 28
mob Avatar answered Nov 14 '22 23:11

mob