Is it possible to conditionally "use bigint" with Perl?
I know I can conditionally use a module in Perl but what about the "pragm开发者_StackOverflowas"? My tests have shown that use bigint
can be much slower than normal math in Perl and I only need it to handle 64-bit integers so I only want to use it when Perl wasn't built with 64-bit integer support, which I also know how to check for using the Config
module.
I tried various things with eval
and BEGIN
blocks but couldn't work out a way to conditionally use bigint. I know I can use Math::BigInt
but then I can't use a single codepath for both the bigint and 64-bit cases.
This actually works just fine:
use Config;
BEGIN {
if (! $Config{use64bitint}) {
require bigint;
bigint->import;
}
}
The interaction between different compile-times is complicated (maybe I'll come back and try to explain it later) but suffice it to say that since there's no string eval here, the flag that bigint sets will persist through the rest of the file or block that you put that BEGIN block inside.
You can take hobbs' answer and stick it in a module.
package int64;
use Config;
sub import {
if (! $Config{use64bitint}) {
require bigint;
bigint->import;
}
}
1;
Then use int64
will do what you mean. Even though bigint is lexical, calling it inside another import routine will make it pass along its magic.
Use the if module. It uses goto
to hide its own stack frame, so it's as if the pragma was called directly.
The solutions given previously may work for bigint
and most pragmas, but they will fail for import
functions that use caller
.
精彩评论