Perl sub 未导出到模块

Perl sub not exported to a module

我编写了一个 perl 模块,它使用 MIME::Base64 中的 encode_base64 函数。出于某种原因,encode_base64 没有被导出到我的模块的命名空间中。

我可能遗漏了什么,但我希望有人能解释它是什么。

这是我的模块:

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;

我在此处的测试脚本中使用该模块:

#!/usr/bin/env perl

use lib '..';
use b64_test;

my $str = "Test";

enc($str);

当我调用测试脚本时,我得到 Undefined subroutine &b64_test::encode_base64 called at b64_test.pm line 18.

为了确保我的机器没有问题,我制作了另一个使用 MIME::Base64 的测试脚本,这个脚本运行良好:

#!/usr/bin/env perl

use MIME::Base64;

my $encoded = encode_base64("TEST");
print $encoded . "\n";

这让我相信它与模块 sub 导出到其他模块的方式有关,但我不知道。任何人都可以阐明这一点吗?

解决方法:package b64_test;放在模块的顶部。

包语句将编译单元声明为在给定的命名空间中。包声明的范围是从声明本身到封闭块、eval 或文件的末尾,以先到者为准。

在你的情况下,你首先有 used 模块并定义了创建另一个命名空间的包。因此脚本无法找到方法。


模块: b64_test.pm

chankeypathak@Whosebug:~$ 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.pl

chankeypathak@Whosebug:~$ cat test.pl

#!/usr/bin/env perl    
use lib '.';
use b64_test;

my $str = "Test";

enc($str);

输出:

chankeypathak@Whosebug:~$ perl test.pl
VGVzdA==