Setting a perl exported constant

Viewed 55

I am using a module (Mail::SPF::Iterator) which exports a constant to enable debugging output:

use Mail::SPF::Iterator Debug =>1; # enable debugging

How can I set this constant later in the code for example depending on a condition?

if ( my condition ) {
   # set Debug to 1
}
2 Answers

The arguments to use are just arguments to the import method of the used package. The use command is run at compile time, so either use a BEGIN block

BEGIN {
    my $do_i_want_to_debug = ... ;
    use Mail::SPF::Iterator Debug => $do_i_want_to_debug;
}

or, if you don't know everything needed to decide the value at compile time, use require instead of use:

my $do_i_want_to_debug = ... ;
require Mail::SPF::Iterator;
Mail::SPF::Iterator->import(Debug => $do_i_want_to_debug);

A Perl constant is usually just a subroutine definition, so you would say

if (condition) {
    no warnings 'redefine';
    *Debug = sub () { 1 };
}
Related