Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Detecting if a scalar has a number or string

by water (Deacon)
on Nov 18, 2004 at 02:23 UTC ( [id://408679]=note: print w/replies, xml ) Need Help??


in reply to Detecting if a scalar has a number or string

# untested! use Regexp::Common; sub isnumeric { my ($x) = @_; # force stringification, if $x is an object. my $s = "$x"; # determine if numberish. roll-your-own or i prefer CPAN. return $s =~ /$RE{num}{real}/; }
of course, the assumption above is that an object that stringifies to a number will support other number-like operations, like == or  + , -, * etc.

if you can't make that assumption, then you'd need to test if the scalar is an object, and if so, use it in various math contexts w/in an eval loop to see if the object supports the overloaded math ops you need. ack.

even that is an assumption -- let's say the object doesn't throw an exception when  +=0 or  *=1. even in this case, you don't know the overloaded op is doing what you think: the object may have overloaded * to mean convolution or scalar product or who-knows-what, rather than common multiplication.

so....

it depends on how much you can assume. in most cases, i'd be comfortable assuming that if an object stringifies to something numberlike, it's worth trying to use it as a number.

and  eval is your friend, so if you assume wrong, you can trap and respond gracefully.

water

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-19 08:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found