Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re^3: Detecting if a scalar has a number or string

by davido (Archbishop)
on Nov 18, 2004 at 23:52 UTC ( #408918=note: print w/ replies, xml ) Need Help??

in reply to Re^2: Detecting if a scalar has a number or string
in thread Detecting if a scalar has a number or string

If it acts just like a number as far as Perl is concerned, then it's a number as far as I'm concerned.

You can let Perl tell you what it thinks then...

#!perl use strict; use warnings; sub seems_like_number { my $thing = shift; use warnings qw/FATAL all/; # Promote warnings to fatal, so # they can be trapped. The effect is # lexically scoped. eval { $thing += 0; }; return $@ ? 0 : 1; } while ( <DATA> ){ chomp; if( seems_like_number( $_ ) ) { printf "%10s seems like a number.\n", $_; } else { printf "%10s doesn't seem like a number.\n", $_; } } __DATA__ 1234 1.234 -2.345 1-1+2 0.032 .321 ASDF ASDF1234 1234ASDF

The first line after __DATA__ is intentionally blank, to test whether or not an empty string will qualify as a number... and of course it won't.

Ok, now if Perl thinks it's not a number, you'll know about it, and if Perl doesn't object to it being considered a number, you'll know that too.


Comment on Re^3: Detecting if a scalar has a number or string
Download Code
Re^4: Detecting if a scalar has a number or string
by tye (Cardinal) on Dec 15, 2004 at 18:54 UTC

    Note that looks_like_number() tells you exactly the same thing, just without all of the overhead. (:

    - tye        

      For the record, you're absolutely right. Scalar::Util's looks_like_number() is 655% faster than my eval trap fatal warning approach. But for some reason I do get a sort of a kick out of the idea of letting perl (the interpreter) tell me if a scalar is a number, rather than Perl (the script). Consider my solution purely an academic enveavor, and use the module for production code.

      The benchmark script:

      The results:

      Rate Seems Looks Seems 38.8/s -- -87% Looks 297/s 665% --


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2014-07-13 22:21 GMT
Find Nodes?
    Voting Booth?

    When choosing user names for websites, I prefer to use:

    Results (252 votes), past polls