Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

check if its a number

by m.y (Novice)
on Apr 12, 2008 at 00:26 UTC ( [id://679897]=perlquestion: print w/replies, xml ) Need Help??

m.y has asked for the wisdom of the Perl Monks concerning the following question:

What is a quick and efficient way to check if a variable is a number? Is it possible to do this without regular expressions? The number can be between 0 and 10.

Replies are listed 'Best First'.
Re: check if its a number
by snoopy (Curate) on Apr 12, 2008 at 00:33 UTC
      > Scalar::Util's looks_like_number method will do what you want.
      

      Scalar::Util uses a regex to get the answer. I'm not sure why snoopy's request has that requirement, but...

      ben@Tyr:~$ perl -wne'print if /sub looks_like_number/../}/' `perldoc - +l Scalar::Util` sub looks_like_number { local $_ = shift; # checks from perlfaq4 return 0 if !defined($_) or ref($_); return 1 if (/^[+-]?\d+$/); # is a +/- integer return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/); # +a C float return 1 if ($] >= 5.008 and /^(Inf(inity)?|NaN)$/i) or ($] >= 5.006 +001 and /^Inf$/i); 0; }
      
      -- 
      Human history becomes more and more a race between education and catastrophe. -- HG Wells
      
Re: check if its a number
by dragonchild (Archbishop) on Apr 12, 2008 at 00:34 UTC
    Why is a regular expression bad? They're extremely efficient and simple to understand and the right tool for the job.
    if ( defined($x) && length($x) && $x !~ /\D/ && 0 <= $x && $x <= 10 ) +{ # It matches }
    Of course, if this is homework, be prepared to explain why each of those is important. :-)

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      I think I will go with the regexp as several people suggested. Originally I didn't want to do that because I remembered a while back I did some benches on using regexp vs substr+index and the regexp was always slower. This code is to run in a mod_perl handler which handles a ton of requests and I was worried about it slowing everything down. thanks
Re: check if its a number
by ysth (Canon) on Apr 12, 2008 at 01:15 UTC
    What do you mean by "is a number"? Between inclusively or exclusively? Is "01" ok? What about "000000000000000000000001"?

    Here's one bad way:

    $isanum = !($x !~ y/.//) + $x =~ y/0-9// == $x =~ y/0-9.//c + $x !~ y/ +0-9// + length($x) && $x <= 10;
Re: check if its a number
by AV-2 (Novice) on Apr 12, 2008 at 02:13 UTC
    I was going to post something else, but in the process I tried this:
    my $foo = 'name'; print $foo + 1;
    Perl warns me "Argument "name" isn't numeric in addition (+)" How does Perl know it isn't a number? Is the method available through a function?
      Yes you can write a function that tells you if a given string triggers the warning.

      sub perl_thinks_it_is_number { eval { use warnings FATAL => 'numeric'; no warnings 'void'; 0+shift; 1; } } print "'foo' isn't a number\n" unless perl_thinks_it_is_number 'foo'; print "'17' is a number\n" if perl_thinks_it_is_number '17';
      Note that this will consider '00' and some other oddities to be a number. You are probably better sticking with other answers elsewhere in this thread.
      ... warning comes up only when using, well, warnings pragma (otherwise string is used as a zero).
Re: check if its a number
by pc88mxer (Vicar) on Apr 12, 2008 at 00:35 UTC
    Why don't you want to use regular expressions?

    Here's an extensive discussion on checking whether a string represents a number: link removed due to copyright concerns.

      Is this link legitimate? Looks like they make a lot of ebooks by many different publishers available on their website, including some texts written by some of the users of this site.

      Martin

        It's not; I reported it to infringement@oreilly.com.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-25 18:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found