Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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

by davido (Cardinal)
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.


Replies are listed 'Best First'.
Re^4: Detecting if a scalar has a number or string
by tye (Sage) 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
Domain Nodelet?
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 drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2021-12-05 18:25 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (31 votes). Check out past polls.