Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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?

Comment on Data::Types or grok_number
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.

    Output:

    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,...


    Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2015-07-31 07:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (275 votes), past polls