Search code examples
perlbackwards-compatibilitybignum

In Perl, how do you detect if bignum support is loaded in versions before 5.9.4?


Perl's bignum bigint and bigrat pragmas helpfully contain an in_effect function that will detect if the pragma is loaded into a scope by probing the hints hash. However, this only works in version 5.9.4 and later of perl, since that's when the lexical hints hash was introduced.

Is there any good way of determining if these pragmas are in effect in earlier versions of perl? For my uses, I would like to support back to version 5.8.8.

Update: mob's solution below will work if I had access to the lexical space where bignum may be in effect. However, for my use case, I am writing a function that will be called from that space, and inside that function I need to determine if the caller's scope has bignum loaded. (ie, in my code I am calling something like bignum::in_effect(2) to look a few frames up the call stack)

 sub test_sub {is_bignum_in_effect_in_the_caller}
              # bignum::in_effect(1) in 5.9.4+

 test_sub(); # no bignum
 {use bignum; test_sub()}  # yes bignum

Solution

  • I don't know if this qualifies as a 'good' way, but you can do a simple operation and see if you are getting the bigint/bigrat result or the conventional Perl result.

    $bigint_enabled = length(1E20) == 21;   # conventional result is 5
    

    At the risk of making this answer even less good, how can you determine whether bigint is enabled in the caller's scope?

    One. Require the caller to tell you whether bignum is enabled.

    # your package
    package Foo;
    use base 'Exporter';
    use bigint;
    our @EXPORT = qw($BIGINT_TEST multiply);
    our $BIGINT_TEST = $]>=5.009004 
        ? "bigint::in_effect()"
        : "\$bigint::VERSION<0.22 || length(1E20)==21";
    
    sub multiply {
        my ($arg1, $arg2, $bigint_enabled) = @_;
        if ($bigint_enabled) {
            use bigint;
            return $arg1*$arg2;
        } else {
            no bigint;
            return $arg1*$arg2;
        }
    }
    
    # user program
    use Foo;
    use bigint;
    print "Enabled: ", multiply(1E15,1E10, eval $BIGINT_TEST), "\n";
    {
        no bigint;
        print "Disabled: ", multiply(1E15,1E10,eval $BIGINT_TEST), "\n";
    }
    
    # result
    $ perl510 user_program.pl
    Enabled: 10000000000000000000000000
    Disabled: 1e+25
    
    $ perl587 user_program.pl      ($bignum::VERSION eq 0.07)
    Enabled: 10000000000000000000000000
    Disabled: 10000000000000000000000000
    
    $ perl588 user_program.pl      (includes upgrade to bignum 0.25)
    Enabled: 10000000000000000000000000
    Disabled: 1e+25
    

    Two. Source filtering? Hack the op tree? Use either of these methods to insert an argument to the method call or to set a global variable prior to the method call.