Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

is_numeric from perlfaq4

by nop (Hermit)
on Oct 07, 2002 at 17:47 UTC ( #203427=perlquestion: print w/ replies, xml ) Need Help??
nop has asked for the wisdom of the Perl Monks concerning the following question:

Hi -- I grabbed the is_numeric function from perfaq4. Either I am using it wrong, or it doesn't work. The following code asserts that undef and fish are numeric. What's going wrong? Thanks -- nop
use POSIX qw(strtod); use strict; foreach (undef, qw(4 0 fish)) { print $_ , " is numeric? ", is_numeric($_), "\n"; } sub getnum { my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) {return;} else {return + $num;} } sub is_numeric { defined scalar &getnum }

Comment on is_numeric from perlfaq4
Download Code
Re: is_numeric from perlfaq4
by Abigail-II (Bishop) on Oct 07, 2002 at 18:02 UTC
    You never called the function getnum. All you did was returning whether the sub getnum was defined. Which it was.

    You didn't copy the is_numeric function correctly from the faq. It should be:

    sub is_numeric {defined getnum $_ [0]}

    Abigail

Re: is_numeric from perlfaq4
by thelenm (Vicar) on Oct 07, 2002 at 18:06 UTC
    Are you using an older version of Perl? In perlfaq4 for 5.6.1 and 5.8.0, the is_numeric function looks like this (slightly different), and works correctly for your example:
    sub getnum { use POSIX qw(strtod); my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) }

    -- Mike

    --
    just,my${.02}

Re: is_numeric from perlfaq4
by fglock (Vicar) on Oct 07, 2002 at 18:08 UTC

    It works if you use:

    sub is_numeric { defined scalar getnum(@_) }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-12-21 03:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (102 votes), past polls