Re: determining if a scalar is an integer or not
by Andreas.Kamentz other posts by this author
Jan 31 2003 9:02AM messages near this date
view in the new Beta List Site
RE: Win32::lanman?
|
Special Tags
I'd like to supplement the suggestions that came from all sides with a little
subroutine which always worked for me determining whether the scalar is a number
(not only integer) and returning the number if it is one. Once having the $res
number from $val variable , you can always test it for being integer, e.g. by
evaluating the expression
(int abs $res == abs $res)
or, alltogether, checking the $val variable for being integer by the
(isnumber $val && int abs isnumber $val == abs isnumber $val)
expression.
Cheers,
-- Andreas
####################################################
# (isn) isnumber
# Returns decimal value of the contents if argument
# is a number (integer if octal or hexadecimal),
# otherwise returns empty string ('')
####################################################
sub isnumber($) {
local $_ = shift;
return '' unless /^[+-]?(?:\d+\.?\d*|\.\d+)$|^[+-]?0x[0-9a-fA-F]*$/;
s/\+//; my $sign = s/^-// ? '-' : '';
/^0[0-7]*$|^0x[0-9a-fA-F]*$/ ? $sign.oct : $sign.$_*1;
}
To: "Perl-Unix-Users \(E-mail\)" <perl-unix-users@[...].com>
"Perl-Win32-Users \(E-mail\)" <perl-win32-users@[...].com>
cc: (bcc: Andreas Kamentz/DE/DELCO)
Subject: determining if a scalar is an integer or not
Good Day All
How can one determine if a variable is a int or not.
e.g.
my $var1 = 100;
my $var2 = "Hello";
How do I determine if $var1 is an integer and $var2 is a string?
Ronald
|