How can I use arbitrary length integers in Perl?
Asked Answered
P

2

7

Is there any standard way to use integers of arbitrary length in Perl? I am working on code that generates x64 assembly for tests, and I'm tired of manipulating 32 bits at a time.

I'm using Perl 5.10.0, for what it's worth.

Pellet answered 24/1, 2010 at 8:22 Comment(0)
B
10

If you only want to use big integers, you can use the bigint, which you can scope to a file:

 use bigint;

or just a limited scope:

 {
 use bigint;
 ...;
 }

If you need big floating point numbers as well as big integers, you can use the bignum pragma in the same way. Either way, these will slow down your program slightly (or significantly if you are doing a lot of math), so you should only use them for the parts where you really need them. However, faster isn't better than correct. :)

If you want very precise control over which numbers use the big* math, you can use the underlying classes that implement them and create objects yourself rather than applying the big* semantics to everything. Look that Math::Big* modules.

I talk about this more in the Benchmarking chapter of Mastering Perl since computers are too fast nowadays to use a factorial as a slow function, and we also added a section on big numbers it to the upcoming Effective Perl Programming, 2nd Edition.

Brockwell answered 24/1, 2010 at 17:33 Comment(0)
N
15

use Math::BigInt

Nad answered 24/1, 2010 at 8:31 Comment(2)
and possibly use bigint; which makes every numeric literal in its scope a BigInt without Math::BigInt->new. Use with care, of course.Shebashebang
Or use bignum;, which extends bigint with BigFloat.Cope
B
10

If you only want to use big integers, you can use the bigint, which you can scope to a file:

 use bigint;

or just a limited scope:

 {
 use bigint;
 ...;
 }

If you need big floating point numbers as well as big integers, you can use the bignum pragma in the same way. Either way, these will slow down your program slightly (or significantly if you are doing a lot of math), so you should only use them for the parts where you really need them. However, faster isn't better than correct. :)

If you want very precise control over which numbers use the big* math, you can use the underlying classes that implement them and create objects yourself rather than applying the big* semantics to everything. Look that Math::Big* modules.

I talk about this more in the Benchmarking chapter of Mastering Perl since computers are too fast nowadays to use a factorial as a slow function, and we also added a section on big numbers it to the upcoming Effective Perl Programming, 2nd Edition.

Brockwell answered 24/1, 2010 at 17:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.