簡體   English   中英

Perl 模塊創建 - 未定義的子程序

[英]Perl Module Creation - Undefined subroutine

我是 perl 新手,我正在嘗試做這個練習,但它不起作用。

這是我創建的模塊。

#!/usr/bin/perl 
use warnings;
use strict;

package Prepare;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw( clean my_print );

sub clean{
    return chomp($_[0]);
}

sub my_print{
    return print("The Results: $_[0]\n");
}

1;

這是我的腳本test_lib.pl

#!/usr/bin/perl
use warnings;
use strict;

use lib '/home/foobar/code';
use My::Prepare;

print "Enter a word: ";
my $input=<STDIN>;

print "You entered: $varia";

clean($input);
my_print($input);

我收到此錯誤:

Undefined subroutine &main::clean called at ./test_lib.pl line 13,  line 1.

在包命名方面,需要達成三點共識:

  • 包文件的位置和名稱

  • 包文件中的語句中的名稱(命名空間)

  • 使用它的代碼中包的use語句

他們需要“同意”如下。

如果其文件中的包聲明是package My::Package; 那么這個包需要作為use My::Package ,它的文件是My目錄下的Package.pm

這個目錄My本身需要位於解釋器將搜索的位置,或者我們需要通知它在哪里查找。 自定義包通常不在默認搜索的目錄中,這就是lib pragma的用途:使用您的

use lib '/home/foobar/code';

我希望My目錄(其中包含Package.pm位於/home/foobar/code目錄中。

然后這是您的示例,具有固定名稱和更多調整。

文件/home/foobar/code/My/Prepare.pm

package My::Prepare;

use warnings;
use strict;

use Exporter qw(import);

our @EXPORT_OK = qw( clean my_print );

sub clean { chomp(@_); return @_ }

sub my_print { print "The Results: $_[0]\n" }

1;

以及使用此模塊的腳本

#!/usr/bin/perl
use warnings;
use strict;

use lib '/home/foobar/code';

use My::Prepare qw(clean my_print);

print "Enter a word: ";
my $input = <STDIN>;

print "You entered: $input";

my $cleaned_input = clean($input);
my_print($cleaned_input);

請通過添加或刪除合適的路徑組件,將上面的路徑調整為您的實際目錄結構。 My::這個名字特別突出。

一些筆記。

  • 模塊中不需要“shebang”行( #!/usr/bin/perl

  • 使用上面的Exporter更現代一些

  • 我強烈建議使用@EXPORT_OK (而不是@EXPORT ),以便模塊的用戶必須專門導入所有列出的符號。 這對每個人都更好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM