五、方法 Perl類的方法只不過是一個Perl子程序而已,也即通常所說的成員函數。Perl的方法定義不提供任何特殊語法,但規定方法的第一個參數為對象或其被引用的包。Perl有兩種方法:靜態方法和虛方法。 靜態方法第一個參數為類名,虛方法第一個參數為對象的引用。方法處理第一個參數的方式決定了它是靜態的還是虛的。靜態方法一般忽略掉第一個參數,因為它們已經知道自己在哪個類了,構造函數即靜態方法。虛方法通常首先把第一個參數shift到變量self或this中,然后將該值作普通的引用使用。如:
1. sub nameLister { 2. my $this = shift; 3. my ($keys ,$value ); 4. while (($key, $value) = each (%$this)) { 5. print "\t$key is $value.\n"; 6. } 7. } 六、方法的輸出 如果你現在想引用Cocoa.pm包,將會得到編譯錯誤說未找到方法,這是因為Cocoa.pm的方法還沒有輸出。輸出方法需要Exporter模塊,在包的開始部分加上下列兩行: require Exporter; @ISA = qw (Exporter); 這兩行包含上Exporter.pm模塊,并把Exporter類名加入@ISA數組以供查找。接下來把你自己的類方法列在@EXPORT數組中就可以了。例如想輸出方法closeMain和declareMain,語句如下: @EXPORT = qw (declareMain , closeMain); Perl類的繼承是通過@ISA數組實現的。@ISA數組不需要在任何包中定義,然而,一旦它被定義,Perl就把它看作目錄名的特殊數組。它與@INC數組類似,@INC是包含文件的尋找路徑。@ISA數組含有類(包)名,當一個方法在當前包中未找到時就到@ISA中的包去尋找。@ISA中還含有當前類繼承的基類名。 類中調用的所有方法必須屬于同一個類或@ISA數組定義的基類。如果一個方法在@ISA數組中未找到,Perl就到AUTOLOAD()子程序中尋找,這個可選的子程序在當前包中用sub定義。若使用AUTOLOAD子程序,必須用use Autoload;語句調用autoload.pm包。AUTOLOAD子程序嘗試從已安裝的Perl庫中裝載調用的方法。如果AUTOLOAD也失敗了,Perl再到UNIVERSAL類做最后一次嘗試,如果仍失敗,Perl就生成關于該無法解析函數的錯誤。 七、方法的調用 調用一個對象的方法有兩種方法,一是通過該象的引用(虛方法),一是直接使用類名(靜態方法)。當然梅椒ū匭胍馴皇涑觥O衷詬鳦ocoa類增加一些方法,代碼如下: package Cocoa; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(setImports, declareMain, closeMain); # # This routine creates the references for imports in Java functions # sub setImports{ my $class = shift @_; my @names = @_; foreach (@names) { print "import " . $_ . ";\n"; } } # # This routine declares the main function in a Java script # sub declareMain{ my $class = shift @_; my ( $name, $extends, $implements) = @_; print "\n public class $name"; if ($extends) { print " extends " . $extends; } if ($implements) { print " implements " . $implements; } print " { \n"; } # # This routine declares the main function in a Java script # sub closeMain{ print "} \n"; } # # This subroutine creates the header for the file. # sub new { my $this = {}; print "\n /* \n ** Created by Cocoa.pm \n ** Use at own risk \n */ \n"; bless $this; return $this; }
|