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; }