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

Hello I have really simple question, is there some function for checking the type of a scalar (string or number)?

I want to do something like:
my ($string, $salt) = @_; $crc = 0xFFFFFFFF; if (defined $salt) { if (isString $salt) { $string = $salt.$string; } elsif (isNumber $salt) { $crc = $salt; } }

Replies are listed 'Best First'.
Re: Checking for data types
by samtregar (Abbot) on Sep 29, 2005 at 15:11 UTC
    There are lots of ways to do this. Here's one which matches how Perl works internally when it needs to decide if something is numeric:

    use Scalar::Util qw(looks_like_number); if (looks_like_number($foo)) { print "It could be a number.\n"; } else { print "It's just a string.\n"; }

    Other solutions could involve regexes from Regexp::Common or coded by hand.

    -sam

Re: Checking for data types
by gryphon (Abbot) on Sep 29, 2005 at 15:10 UTC

    Greetings,

    You could do a regex to check that there aren't any non-digit characters. Just replace your elsif conditional with this:

    elsif ($salt !~ /\D/) {

    But looking at your example, do you want something a little bit more specific? Do you want only numbers in a particular range?

    gryphon
    Whitepages.com Development Manager (DSMS)
    code('Perl') || die;

Re: Checking for data types
by jZed (Prior) on Sep 29, 2005 at 15:40 UTC
    As mentioned by others, you can construct a regex (though it needs to be somewhat complicated if you want to catch all formats of numbers rather than just digits and floats e.g. scientific notation). Scalar::Util::looks_like_number() is easier. If you happen to be using DBI in your script anyway, it has its own implementatin of looks_like_number() so you can use it rather than requiring Scalar::Util.