Search code examples
perlimportmoduleperl-moduleexporter

How to import symbols from a Exporter Perl module using require?


I like to import symbols from an Exporter powered Perl module using require and not use. Perl don't know the variable he just imported.

Perl module sample:

package TheModule;
use strictures;
use base 'Exporter';
use Const::Fast qw( const );
const our $TEST_VAR_1 => 'Test variable 1';
our @EXPORT_OK = qw( $TEST_VAR_1 );
our %EXPORT_TAGS = ( TEST_VAR => [qw( $TEST_VAR_1 )] );

Perl script sample

#!/usr/bin/perl
use strictures;
require TheModule;
TheModule->import( ':TEST_VAR' );
printf "Test variable 1 contains: %s\n", $TEST_VAR_1;

The following example works, but I have to use require instead of use.

#!/usr/bin/perl
use strictures;
use TheModule ( ':TEST_VAR' );
printf "Test variable 1 contains: %s\n", $TEST_VAR_1;

How to import $TEST_VAR_1 within the require environment?


Solution

  • our @EXPORT_TAGS should be our %EXPORT_TAGS. :)


    Alright, there is something else wrong. At compile time, when

    printf "Test variable 1 contains: %s\n", $TEST_VAR_1;
    

    is being transformed into ops, $TEST_VAR_1 does not exist in that scope yet, since

    TheModule->import( ':TEST_VAR' );
    

    is executed only at runtime. So, unless you put a BEGIN{} around your require and import, this cannot work.