On Wed, May 22, 2002 at 10:14:17AM -0700, Chris Angell wrote:
> I have an idea for the int() function. I think it would be cool if it
> returned false/undefined when the argument passed to it is a whole number.
> For example:
>
> int(1) or print "argument passed to int() is something other than a
> decimal number";
>
> A friend came up with this:
>
> sub myint { return if $_[0] =~ /\A\d+\z/; $_[0] =~ /^(\d+)/ ? $1 : 0 }
>
> What do you guys think?
It would be nice to have a way to check if something is an integer better
than the regexes in perlfaq4, but int()'s return value already has a job:
$ perl -wle 'print int(1.5)'
1
$ perl -wle 'print int(2)'
2
if it was changed to return 0 with integers and only truncate floats, you'd
get some very odd and unpredictable behavior:
sub int_add { return int($_[0]) + int($_[1]) }
print int_add(2.5, 2.5); # 4
print int_add(2.0, 2.5); # 4
print int_add(2, 2.5); # 2!
to be safe, you'd always have to shield your int() calls where you want to
truncate.
my $truncated_num = int($num) ? int($num) : $num;
A better way, since we're hopefully going the Everything Is An Object route,
would be to simply have an is_int() method for numbers.
print $num.is_int ? "Integer" : "Float";
--
This sig file temporarily out of order.