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

时间:2016-04-26 12:49:34

标签: 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;

2 个答案:

答案 0 :(得分:4)

删除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';

另见:

答案 1 :(得分:1)

如果您只想要一个容器用于许多实用程序子例程,那么您应该使用Exporter

创建库模块

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

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();
相关问题