I realise, this has been queried before but I can't seem to find a simple elegant Perl example. I need to know if a string is a number or not. With trial and error, I have come up with the below that works. This is anything but elegant and has been separated into multiple if / elsif for testing. I would like to combine the string comparisons into as few as possible but seem to break the code every time I try.
print IsNumber("0777 891 777") . "\n"; # 0 print IsNumber("1.5671") . "\n"; # 1 print IsNumber("121A3D") . "\n"; # 0 print IsNumber("777") . "\n"; # 1 print IsNumber("0") . "\n"; # 1 print IsNumber("-4.567") . "\n"; # 1 print IsNumber("+9.8.97") . "\n"; # 0 print IsNumber("+9.897") . "\n"; # 1 print IsNumber("+9.8¬97") . "\n"; # 0 print IsNumber("9.8[97") . "\n"; # 0 sub IsNumber { my ($string) = @_; my $valid = 0; my $count = $string =~ tr/\.//; if ( $string =~ m/[a-zA-Z\ \[\]]/ ) { $valid = 0; } elsif ( $string =~ /[^\x00-\x7F]/ ) { $valid = 0; } elsif ( $count > 1 ) { $valid = 0; } elsif ( $string =~ m/[#@':;><,.{}[]=!"£$%^&*()]/ ) { $valid = 0; } elsif ( $string =~ m/^[+-]?\d+$/ ) { $valid = 1; } elsif ( $string =~ m/^[+-]?[0-9]+[.]?[0-9]+/ ) { $valid = 1; } return $valid; }

In reply to Is A Number by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.