2009-09-03 28 views

回答

6

還有其他方法,但它們都有嚴重的問題。模塊是要走的路,它們不一定非常複雜。這裏是一個基本的模板:

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

+0

謝謝,這比我在網上找到的更清楚,雖然我不明白所有的出口商的東西,我知道如何使用它的例子。 – 2009-09-05 04:07:22

12

將通用功能放入module。有關詳細信息,請參閱perldoc perlmod

+0

有沒有辦法做到這一點,而不模塊?我不是很擅長perl,我希望有更像javascript-ish的解決方案。 – 2009-09-04 01:11:15

+0

你可以製作圖書館。再一次,我們在我的書中涵蓋了所有這些。 :) – 2009-09-04 16:15:17

2

大約三分之一的Intermediate Perl專門討論這個話題。

+2

這使我感到評論,而不是答案。 – Telemachus 2009-09-04 00:54:43

+0

它引起了我的回答,因爲鏈接到模塊或文檔頁面是一個答案。 – 2009-09-04 00:59:02

+1

@brian:喲,這些都是非常多的評論。 (如果你指的是思南的答案,但我會說他至少有一句話是「把常見的東西放在一個模塊中」。「你只是說,」我的書告訴你如何做到這一點。「你的回答實際上是,現在我看着它,對思南的答案發表評論。) – Telemachus 2009-09-04 11:58:34

0

閱讀更多關於perldoc perlmod模塊和更多Exporter使用模塊是最穩健的方式,並學習如何使用模塊將是有益的。

效率較低的是do函數。提取您的代碼到一個單獨的文件,說「mysub.pl」,並

do 'mysub.pl'; 

這將讀取,然後EVAL文件的內容。

0

可以使用

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.pltest2.pl將產生以下結果:

149$ test.pl 
starting test.pl 
asdfasfdas 

150$ test2.pl 
starting test2.pl 
1 
相關問題