In Perl, how can I tell if a string is a number?

后端 未结 7 941
青春惊慌失措
青春惊慌失措 2021-02-14 22:33

I am using Perl to convert some XML to JSON. If the XML attribute is a number, I don\'t want to put quotes around it so that JSON will treat it as a number and not a string. How

相关标签:
7条回答
  • 2021-02-14 22:44

    You could just force it into a number then compare that to the original string.

    if( $value eq $value+0 ){
      print "$value is a number\n";
    }
    

    ( Note: it will only work for simple numbers, like 123 or 12.3 )

    0 讨论(0)
  • 2021-02-14 22:46

    I think this question from perlfaq solves your problem.

    Generally the problem is defining what exactly you want to read as number.

    • is "-1.312" valid number?
    • is "inf"?
    • 5.34123412E-03 ?
    0 讨论(0)
  • 2021-02-14 22:47

    It might be easier for you to just read the XML into a data structure in Perl and let Perl's JSON library figure it out for you. It already has checking for that, so unless your number is actually a string in the XML (e.g. it's got a space after it, etc) JSON->encode() will encode it as a JSON number.

    0 讨论(0)
  • 2021-02-14 22:48

    The JSON specification provides fairly clear rules on the format of a number, so the following regex should work:

    /^-?(0|([1-9][0-9]*))(\.[0-9]+)?([eE][-+]?[0-9]+)?$/
    
    0 讨论(0)
  • 2021-02-14 22:51

    Try Scalar::Util::looks_like_number:

    E.g.:

    use Scalar::Util qw(looks_like_number);
    
    if (looks_like_number($thingy)) {
        print "looks like $thingy is a number...\n"
    }
    
    0 讨论(0)
  • 2021-02-14 22:55

    Assuming you don't need to support unusual stuff (like sci-notation) this almost works (and is very simple):

    #!/usr/bin/perl
    
    my $foo = '1234.5';
    
    if( $foo =~ /\d+/ ){
        print "$foo is a number\n";
    }
    

    The reason it doesn't fully work is because you can have hyphens and dots anywhere (as many as you please) as long as you have at least one digit present). '--1--2' evaluates as zero, and '1.2.3.4.5' evals as 1.2 (the second dot and everything after are ignored). This may or may not be an issue for you.

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