我正在维护几个Perl脚本,它们都具有用于不同功能的类似代码块。每次更新代码块时,我都必须通过每个脚本并手动进行更改。有没有办法将通用Perl函数封装到自己的脚本中?
有没有办法将通用函数封装到自己的脚本中并调用它们?
我正在维护几个Perl脚本,它们都具有用于不同功能的类似代码块。每次更新代码块时,我都必须通过每个脚本并手动进行更改。有没有办法将通用Perl函数封装到自己的脚本中?
有没有办法将通用函数封装到自己的脚本中并调用它们?
还有其他方法,但它们都有严重的问题。模块是要走的路,它们不一定非常复杂。这里是一个基本的模板:
package Mod;
use strict;
use warnings;
use Exporter 'import';
#list of functions/package variables to automatically export
our @EXPORT = qw(
always_exported
);
#list of functions/package variables to export on request
our @EXPORT_OK = qw(
exported_on_request
also_exported_on_request
);
sub always_exported { print "Hi\n" }
sub exported_on_request { print "Hello\n" }
sub also_exported_on_request { print "hello world\n" }
1; #this 1; is required, see perldoc perlmod for details
创建一个目录,如/home/user/perllib
。将该代码放在该目录中名为Mod.pm
的文件中。你可以使用这样的模块:
#!/usr/bin/perl
use strict;
use warnings;
#this line tells Perl where your custom modules are
use lib '/home/user/perllib';
use Mod qw/exported_on_request/;
always_exported();
exported_on_request();
当然,你可以命名文件任何你想要的。将文件包命名为相同文件是一种很好的形式。如果您想要在包名中包含::
(如File::Find
),则需要在/home/user/perllib
中创建子目录。每个::
相当于/
,所以My::Neat::Module
将进入文件/home/user/perllib/My/Neat/Module.pm
。您可以在perldoc Exporter
将通用功能放入module。有关详细信息,请参阅perldoc perlmod
。
有没有办法做到这一点,而不模块?我不是很擅长perl,我希望有更像javascript-ish的解决方案。 – 2009-09-04 01:11:15
你可以制作图书馆。再一次,我们在我的书中涵盖了所有这些。 :) – 2009-09-04 16:15:17
大约三分之一的Intermediate Perl专门讨论这个话题。
这使我感到评论,而不是答案。 – Telemachus 2009-09-04 00:54:43
它引起了我的回答,因为链接到模块或文档页面是一个答案。 – 2009-09-04 00:59:02
@brian:哟,这些都是非常多的评论。 (如果你指的是思南的答案,但我会说他至少有一句话是“把常见的东西放在一个模块中”。“你只是说,”我的书告诉你如何做到这一点。“你的回答实际上是,现在我看着它,对思南的答案发表评论。) – Telemachus 2009-09-04 11:58:34
阅读更多关于perldoc perlmod
模块和更多Exporter
使用模块是最稳健的方式,并学习如何使用模块将是有益的。
效率较低的是do
函数。提取您的代码到一个单独的文件,说“mysub.pl”,并
do 'mysub.pl';
这将读取,然后EVAL文件的内容。
可以使用
require "some_lib_file.pl";
,你就会把你的所有常用功能,并从其中将包含上述行其他脚本调用它们。
例如:
146$ cat tools.pl
# this is a common function we are going to call from other scripts
sub util()
{
my $v = shift;
return "$v\n";
}
1; # note this 1; the 'required' script needs to end with a true value
147$ cat test.pl
#!/bin/perl5.8 -w
require 'tools.pl';
print "starting $0\n";
print util("asdfasfdas");
exit(0);
148$ cat test2.pl
#!/bin/perl5.8 -w
require "tools.pl";
print "starting $0\n";
print util(1);
exit(0);
然后执行test.pl
和test2.pl
将产生以下结果:
149$ test.pl
starting test.pl
asdfasfdas
150$ test2.pl
starting test2.pl
1
谢谢,这比我在网上找到的更清楚,虽然我不明白所有的出口商的东西,我知道如何使用它的例子。 – 2009-09-05 04:07:22