Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
# 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


In reply to Re: Detecting if a scalar has a number or string by water
in thread Detecting if a scalar has a number or string by rrwo

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-25 23:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found