For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2005 > is_int









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author is_int
Mads N. Vestergaard

2005-07-24, 8:29 pm

Hi everybody,

I'm trying to check weather a variable is an integer, i have tried the
following:

use Math::BigRat;
my $x = 42;
print "$x is an integer\n" if $x->is_int();

But it doesn't work, it gives me the error:

Can't call method "is_int" without a package or object reference at
test.pl line 3.

Can somebody give me a hint what i am doing wrong, or is there a better
way to check if a variable is numeric ?


Thanks

Mads

--
Mads N. Vestergaard - http://rwxr-xr-x.dk
Interested in Open Source, and web application development
Jeff 'japhy' Pinyan

2005-07-24, 8:29 pm

On Jul 23, Mads N. Vestergaard said:

> I'm trying to check weather a variable is an integer, i have tried the
> following:
>
> use Math::BigRat;
> my $x = 42;
> print "$x is an integer\n" if $x->is_int();


Using Math::BigRat doesn't automatically make numbers into objects. You'd
have to say

my $x = Math::BigRat->new(42);

in order to call the is_int() method. But there's no need to go through
those hoops.

Depending on what your definition of an integer is, you can probably just
do:

if ($x eq int($x)) {
# it's an integer
}

This will fail if $x is something like '00' or '1e0'.

--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com