Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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 }

Replies are listed 'Best First'.
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]}


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


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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://203427]
Approved by Ovid
NodeReaper says "Shhhh! Be vewy vewy quiet, I'm hunting wumpus"

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2018-03-23 00:12 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (286 votes). Check out past polls.