Search code examples
perlenumsexporter

Weirdness exporting constants created with enum::fields in perl


I've created two test modules, X.pm and X2.pm. The X.pm module works. The X2.pm module doesn't, at least not like I'd expect it to.

X.pm

package X {

    use enum::fields qw(I_VAL);
    use parent qw(Exporter);

    our @EXPORT = qw(I_VAL);
}

X2.pm

package X2 {

    our @EXPORT = qw(I2_VAL);

    use enum::fields (@EXPORT);
    use parent qw(Exporter);

}

The test program is:

use X;
use X2;

printf("I_VAL = %d\n", I_VAL);
printf("I2_VAL = %d\n", I2_VAL);

And the output is:

bash$ ./tmp/testit
I_VAL = 0
Undefined subroutine &X2::I2_VAL called at /home/bennett/tmp/testit line 15.

The real project has several dozen enum::fields, and X2.pm is my attempt to keep the enumerations in sync with the exports.

My questions are these:

  • Why doesn't X2 work? Is it exporting(importing) before enum::fields runs?
  • What do I do about it?

Solution

  • Use statements are executed as soon as they are compiled, so

    use enum::fields (@EXPORT);
    

    is executed before

    our @EXPORT = qw(I2_VAL);
    

    This would work:

    package X3;
    
    use strict;
    use warnings;
    
    my @enum; BEGIN { @enum = qw( I2_VAL ); }
    
    use Exporter     qw( import );
    use enum::fields @enum;
    
    our @EXPORT = @enum;
    
    1;