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+$/;.