Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Integer Type Checking

by HiFoo (Scribe)
on Jul 19, 2002 at 17:14 UTC ( [id://183319]=perlquestion: print w/replies, xml ) Need Help??

HiFoo has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to determine if a scalar variable is an integer or a string?

In a shell script I am porting:

expr $VAR + 1; if [ $? -ne 0 ]; then do stuff... fi

was used to check to see if the value of the variable was an integer.

Is there a similar way to do this in Perl?

Thanks

Replies are listed 'Best First'.
Re: Integer Type Checking
by insensate (Hermit) on Jul 19, 2002 at 17:37 UTC
    Remember... -6 is an integer...and in some cases you may want +5 to be one too...so
    print "Integer!" if /^[+-]?\d+$/;

    Jason
Re: Integer Type Checking
by mkmcconn (Chaplain) on Jul 19, 2002 at 18:38 UTC

    For more reliable type checking, there is Data::Types

    "This module exports a number of functions that are useful for validating and converting data types. It is intended for use in applications where data types are more important than they typically are in Perl -- e.g., database applications."
    mkmcconn
    P.S. also check out Damian's Attribute::Types

Re: Integer Type Checking
by Nightblade (Beadle) on Jul 19, 2002 at 17:23 UTC
    if($VAR =~ m/^\d+$/) { # Integer } else { # Not integer }
Re: Integer Type Checking
by simeon2000 (Monk) on Jul 19, 2002 at 17:26 UTC
    Perl doesn't differentiate, AFAIK, between strings and integers as far as the programmer is concerned.

    One way to tell if it's an integer would be:

    print "Integer!" if $VAR =~ /^\d+$/;.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-04-18 06:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found