如何从另一个 perl 文件添加库



我想将一个库导入到我的perl脚本中。以下是我的尝试:

function.pl

#!/usr/bin/perl
package main; 
use strict;
use warnings;
use 5.005;
use Term::ANSIColor qw(:constants); 
use LWP::Simple;    
use diagnostics;
use File::Spec;
use Getopt::Long;
use File::Basename;
use Cwd 'abs_path';
sub myfunction {
    print RED, " Deleting...", RESET;
    system("rm –f /file_location/*.");
    print "deleted.n";      
}

我想在这个新的perl脚本中导入 function.pl。

#!/usr/bin/perl    
package main; 
myfunction;
myfunciton2;

删除该package main; - 不需要。

最佳实践方法(但不是最简单的方法):

创建一个新目录 MyApp(替换为应用程序的一些唯一名称),并将文件 Global.pm 放入此目录中:

package MyApp::Global; # Same name as Directory/File.pm!
use strict;
use warnings;
use Exporter;
use Term::ANSIColor qw(:constants);
our @ISA       = ('Exporter');
our @EXPORT_OK = qw(myfunction);
sub myfunction {
    print RED, " Deleting...", RESET;
    system("rm –f /file_location/*.");
    print "deleted.n";  
}
1; # Important!
插入

到两个文件(function.pl 和 newone.pl)的使用行之后:

use MyApp::Global qw(myfunction);

基本方法(类似PHP:更简单,但不是"最佳实践"):

创建文件 global.pl(或任何其他名称):

use strict;
use warnings;
use Term::ANSIColor qw(:constants);
sub myfunction {
    print RED, " Deleting...", RESET;
    system("rm –f /file_location/*.");
    print "deleted.n";  
}
1; # Important!

use行之后插入到两个文件(function.pl 和 newone.pl)中:

require 'global.pl';

另请参阅:

  • http://search.cpan.org/perldoc?Exporter
  • http://www.perlmonks.org/?node_id=102347(感谢@Arunesh辛格)
  • http://perldoc.perl.org/perlmod.html

如果您只需要一个用于多个实用程序子例程的容器,那么您应该使用 Exporter 创建一个库模块

将包和模块文件命名为 main 以外的名称,这是主程序使用的默认包。在下面的代码中,我编写了包含package Functions的模块文件Functions.pm。名称必须匹配

Functions.pm

package Functions;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw/ my_function /;
use Term::ANSIColor qw(:constants); 

sub my_function {
    print RED, " Deleting...", RESET;
    system("rm –f /file_location/*.");
    print "deleted.n";      
}
1;

program.pl

#!/usr/bin/perl    
use strict;
use warnings 'all';
use Functions qw/ my_function /;
my_function();

最新更新