Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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.


Dave


Comment on Re^3: Detecting if a scalar has a number or string
Download Code
Replies are listed 'Best First'.
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% --

      Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (15)
As of 2015-07-31 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls