Search code examples
perlperl-module

Perl throws undefined subroutine in module instead of correct error


I've moved part of a script into a module, and now the only error I get when I do something wrong is "Undefined subroutine", even when the real error is that I misspelled a variable, or forgot a closing paren, or left off a semi-colon.

The only way to find the real error is to copy the entire thing into a script and run it that way. It's very tedious. Am I doing something wrong, or is this just the way modules are supposed to work?

Here is a very simple example that shows the problem:

Module:

#!/usr/bin/env perl 

package CalledError;
use Exporter qw(import);

our @EXPORT_OK=qw(do_build_stor_pools);

use strict;
use warnings;
use feature qw(say);

sub do_build_stor_pools {
    say "now in CalledError do_build_stor_pools";

    #my $undef_var="uncomment this to fix";
    say $undef_var;

    return;
}

Calling script:

#!/usr/bin/env/perl 

use strict;
use warnings;

my $buildstor_mod="CalledError";
eval "require $buildstor_mod";
$buildstor_mod->import();

CalledError::do_build_stor_pools();

Run it like this to get Undefined subroutine &CalledError::do_build_stor_pools called at calling_test.pl line 11.

Uncomment the definition of $undef_var to make it work.


Solution

  • If you checked $EVAL_ERROR, you would see the real error:

    #!/usr/bin/env/perl 
    
    use strict;
    use warnings;
    
    my $buildstor_mod="CalledError";
    eval "require $buildstor_mod";
    if ($@) {
       die "$@";
    }
    $buildstor_mod->import();
    
    CalledError::do_build_stor_pools();
    

    Error message:

    Global symbol "$undef_var" requires explicit package name at CalledError.pm line 15.
    Compilation failed in require at (eval 1) line 2.
    

    You see the undefined subroutine error because require fails.