How to tell apart numeric scalars and string scalars in Perl?

前端 未结 9 1430
一生所求
一生所求 2020-12-16 12:31

Perl usually converts numeric to string values and vice versa transparently. Yet there must be something which allows e.g. Data::Dumper to discriminate between

相关标签:
9条回答
  • 2020-12-16 12:59

    When a variable is used as a number, that causes the variable to be presumed numeric in subsequent contexts. However, the reverse isn't exactly true, as this example shows:

    use Data::Dumper;
    
    my $foo = '1';
    print Dumper $foo;  #character
    my $bar = $foo + 0;
    print Dumper $foo;  #numeric
    $bar = $foo . ' ';
    print Dumper $foo;  #still numeric!
    $foo = $foo . '';
    print Dumper $foo;  #character
    

    One might expect the third operation to put $foo back in a string context (reversing $foo + 0), but it does not.

    If you want to check whether something is a number, the standard way is to use a regex. What you check for varies based on what kind of number you want:

    if ($foo =~ /^\d+$/)      { print "positive integer" }
    if ($foo =~ /^-?\d+$/)    { print "integer"          }
    if ($foo =~ /^\d+\.\d+$/) { print "Decimal"          }
    

    And so on.

    It is not generally useful to check how something is stored internally--you typically don't need to worry about this. However, if you want to duplicate what Dumper is doing here, that's no problem:

    if ((Dumper $foo) =~ /'/) {print "character";}
    

    If the output of Dumper contains a single quote, that means it is showing a variable that is represented in string form.

    0 讨论(0)
  • 2020-12-16 13:03

    You might want to try Params::Util::_NUMBER:

    use Params::Util qw<_NUMBER>;
    
    unless ( _NUMBER( $scalar ) or $scalar =~ /^'.*'$/ ) { 
       $scalar =~ s/'/''/g;
       $scalar = "'$scalar'";
    }
    
    0 讨论(0)
  • 2020-12-16 13:08

    One simple solution that wasn't mentioned was Scalar::Util's looks_like_number. Scalar::Util is a core module since 5.7.3 and looks_like_number uses the perlapi to determine if the scalar is numeric.

    0 讨论(0)
提交回复
热议问题