Reputation: 49
I have a perl module that I wrote that uses the encode_base64 function from MIME::Base64. For some reason, encode_base64 is not being exported into the namespace of my module.
I am probably missing something but I hope someone can explain what it is.
Here is my module:
use strict;
use Exporter;
use MIME::Base64;
package b64_test;
BEGIN {
our $VERSION = 1.00;
our @ISA = qw(Exporter);
our @EXPORT = qw(enc);
}
sub enc {
my $msg = shift;
my $encoded = encode_base64($msg);
print $encoded . "\n";
}
1;
I am using that module in my test script here:
#!/usr/bin/env perl
use lib '..';
use b64_test;
my $str = "Test";
enc($str);
When I call the test script I get Undefined subroutine &b64_test::encode_base64 called at b64_test.pm line 18.
To make sure there wasn't something wrong with my machine I made another test script that uses MIME::Base64 and this one works fine:
#!/usr/bin/env perl
use MIME::Base64;
my $encoded = encode_base64("TEST");
print $encoded . "\n";
This leads me to believe that it has something to do with how module subs are exported into other modules but I don't know. Can anyone shed some light on this?
Upvotes: 3
Views: 2164
Reputation: 21666
Solution: Put package b64_test;
at the top of the module.
The package statement declares the compilation unit as being in the given namespace. The scope of the package declaration is from the declaration itself through the end of the enclosing block, eval, or file, whichever comes first.
In your case you have use
d module first and defined the package which created another namespace. Therefore the script is unable to find method.
Module: b64_test.pm
chankeypathak@stackoverflow:~$ cat b64_test.pm
package b64_test;
use strict;
use Exporter;
use MIME::Base64;
BEGIN {
our $VERSION = 1.00;
our @ISA = qw(Exporter);
our @EXPORT = qw(enc);
}
sub enc {
my $msg = shift;
my $encoded = encode_base64($msg);
print $encoded . "\n";
}
1;
Test script: test.pl
chankeypathak@stackoverflow:~$ cat test.pl
#!/usr/bin/env perl
use lib '.';
use b64_test;
my $str = "Test";
enc($str);
Output:
chankeypathak@stackoverflow:~$ perl test.pl
VGVzdA==
Upvotes: 7