Is it possible to conditionally “use bigint” with Perl?

喜欢而已 提交于 2019-11-30 23:21:18

问题


I know I can conditionally use a module in Perl but what about the "pragmas"? 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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5310605/is-it-possible-to-conditionally-use-bigint-with-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!