Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Is A Number

by BillKSmith (Monsignor)
on Dec 18, 2021 at 23:25 UTC ( [id://11139711]=note: print w/replies, xml ) Need Help??


in reply to Is A Number

I agree with the other monks that the module is the best solution if you want to know if perl considers your string a number. But I will try to answer your original question. It is actually better to only test for the valid cases, and assume that it is invalid otherwise. The following code is a simplified version of yours.
use strict; use warnings; use Test::Simple tests => 10; sub IsNumber { (local $_) = @_; return (m/^[+-]?\d+$/ or m/^[+-]?[0-9]+[.]?[0-9]+$/) ; } ok( !IsNumber("0777 891 777")); ok( IsNumber("1.5671") ); ok( !IsNumber("121A3D") ); ok( IsNumber("777") ); ok( IsNumber("0") ); ok( IsNumber("-4.567") ); ok( !IsNumber("+9.8.97") ); ok( IsNumber("+9.897") ); ok( !IsNumber("+9.8¬97") ); ok( !IsNumber("9.8[97") );

OUTPUT:

1..10 ok 1 ok 2 ok 3 ok 4 ok 5 ok 6 ok 7 ok 8 ok 9 ok 10
Bill

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139711]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-26 06:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found