Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl namespace problem: using exported functions in modules not working

Tags:

perl

I'm packaging some common functions in a small Perl module, that I load in the script using

use lib path/to/lib

In the module file I imported some other system installed modules (e.g. Carp qw(confess), but I cannot invoke confess directly, but rather Carp::confess, which is unusual to me.

This is my (non)-working example: https://github.com/telatin/bioinfo/blob/master/mini/script.pl

use 5.012;
use FindBin qw($Bin);
use lib "$Bin/Demo/lib";
use Local::Module;

say "Version: ", $Local::Module::VERSION;

Local::Module->new();

The module: https://github.com/telatin/bioinfo/blob/master/mini/Demo/lib/Local/Module.pm

use 5.012;
use warnings;
use Carp qw(confess);
package Local::Module;
$Local::Module::VERSION = 2;


sub new {
    my ($class, $args) = @_;
    my $self = {
        debug   => $args->{debug}, 
    };
    my $object = bless $self, $class;

    confess "Unable to create fake object";
    return $object;
}

1;

What should I do in the .pm file to avoid this problem?

like image 325
Andrea T. Avatar asked Jan 27 '23 02:01

Andrea T.


1 Answers

The problem is here:

use 5.012;
use warnings;
use Carp qw(confess);
package Local::Module;

First you load Carp and import confess, but at that point you're still in package main, so confess is imported into main.

Then you switch packages with package Local::Module, but there is no confess function defined here.

You need to switch packages first:

package Local::Module;
use 5.012;
use warnings;
use Carp qw(confess);

Now all imports and all the following code are in the same package.

like image 50
melpomene Avatar answered Jan 31 '23 04:01

melpomene