John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

Turning a string into an integer, there is literally nothing to it in Perl since the string is a number if used as such. Turning a string into a BigInt is done with BigInt->new. OK.

I'm thinking I have a list of numbers and occasionally one might be too big to handle without loss of precision. So I'd like to make my strings into normal numbers or into BigInts if they are large. But, without doing a lot of work of parsing which is what's normally built-in, how do I tell if the number will fit into a normal integer?

On a practical basis, I can probably just use the length (how many digits). But I still wonder if there is any kind of more-transparant support for numbers to turn into bigint/bigfloat automatically like is planned for Perl 6, or if I overlooked some "smart" conversion function.

Replies are listed 'Best First'.
Re: BigInt, some of the time
by Zaxo (Archbishop) on Feb 03, 2004 at 23:43 UTC

    One simple way is to use Math::BigInt for all of them. use Math::BigInt ':constant', lib => 'Pari,GMP'; That will make all integers bigints, and use the high-test libs if available. That will help make up for the overhead.

    After Compline,
    Zaxo

Re: BigInt, some of the time
by tachyon (Chancellor) on Feb 03, 2004 at 23:42 UTC
    my $LIM = 2**32 -1; my $int = $num > $LIM ? Math::BigInt->new($num) : $num;

    Another solution is to just compile perl with 64 bit support which give you really big ints....

    cheers

    tachyon

      Last I heard, the Win32 build did not support 64-bit. I've often wished the Q format was supported by pack/unpack since win32 has some 64-bit values.