Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Data::Types or grok_number

by tqisjim (Beadle)
on Sep 25, 2012 at 16:27 UTC ( #995587=perlquestion: print w/replies, xml ) Need Help??
tqisjim has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to find functions similar to Data::Types::is_int

From what I gather, these functions are implemented via Regex. I would prefer to use the built-in functions SvIOK, SvNOK, and SvPOK. I found a reference to grok_number, but the documentation is really sketchy. I'd prefer not to use a home-rolled version. Any suggestions?

Replies are listed 'Best First'.
Re: Data::Types or grok_number
by tobyink (Abbot) on Sep 25, 2012 at 16:37 UTC
    use 5.010; use Scalar::Util qw(looks_like_number); sub is_int (_) { my $i = shift; looks_like_number($i) and int($i)==$i; } say for grep { is_int } qw( -6 5.2 5.0 3e4 0Hello );

    Note that this classes 5.0 as an integer, which is correct from a maths point of view, but not necessarily from a comp sci one.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      I was thinking of something along the lines of the following:

      print TQIS::Primitive::typeis("1") ; > string print TQIS::Primitive::typeis(1) ; > integer
      Here is the code:
      #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" SV* typeis ( SV* what ) ; SV* typeis ( SV* what ) { if ( SvIOK( what ) ) return newSVpvs( "integer" ) ; else if ( SvNOK( what ) ) return newSVpvs( "double" ) ; else if ( SvPOK( what ) ) return newSVpvs( "string" ) ; return newSVpvs( "unknown" ) ; } MODULE = TQIS::Primitive PACKAGE = TQIS::Primitive PROTOTYPES: ENABLE SV* typeis( what ) SV* what
Re: Data::Types or grok_number
by Kenosis (Priest) on Sep 25, 2012 at 17:50 UTC

    Here's another option using Regexp::Common:

    use strict; use warnings; use Regexp::Common qw/ number /; print for grep /^$RE{num}{int}$/, <DATA>; __DATA__ 3.14 10 -42 42 .14159 12.34e-56 3.0 Hello, world.


    10 -42 42
Re: Data::Types or grok_number
by davido (Archbishop) on Sep 26, 2012 at 03:28 UTC

    How about Scalar::Util::Numeric?

    This module exports a number of wrappers around perl's builtin grok_number function,...


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://995587]
Approved by Happy-the-monk
and nobody stirs...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2017-08-18 02:14 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (294 votes). Check out past polls.