Search code examples
perlperl-module

Undefined subroutine in perl &library1::func1


I am calling a function (func1) from library2.pm in library1.pm. And the function is called simply as &func1(), since I declared " use library2 " in library1. But this is throwing an error as the undefined subroutine. But when I am calling that function as " &library2::func1 " it is working. Am I missing any Perl package here?


Solution

  • Did you export the function? It's hard to tell what you're missing since you didn't post any code! I could explain why you need what's missing if I knew what it was. Instead, you'll have to settle for an example of what's needed.

    library2.pm should include:

    package library2;
    
    use strict;
    use warnings;
    
    use Exporter qw( import );
    
    our @EXPORT = qw( func1 );
    
    ...
    
    sub func1 { ... }
    
    ...
    
    1;
    

    library1.pm should include:

    package library1;
    
    use strict;
    use warnings;
    
    use library2;
    
    ...
    
    func1(...)
    
    ...
    
    1;
    

    By the way, the name of the language is Perl, not PERL. It's not an acronym.


    By the way, you should stop using & in front of sub calls; there's no reason to tell Perl to ignore the prototypes of the subs you call.


    By the way, lower-case module names are technically reserved for use by Perl. But more importantly, convention reserves lower-case modules for pragma modules (modules that affect the language, and modules that are lexically-scoped in effect). Please avoid lower-case module names.


    By the way,

    use library2 qw( func1 );
    

    is generally better than

    use library2;
    

    because it's easier to see where subs are defined, and it prevents surprises if the default exports of a module ever change.