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

前端 未结 9 1436
一生所求
一生所求 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.

提交回复
热议问题