Perl的物件導向方法

物理狂人發表於2012-05-04
{ package LivingCreature;
sub speak{
my $class = shift;
my $gender = shift;
print "a $gender $class goes ", $class->sound, "!\n";
}
}

{ package Animal;
@ISA = qw(LivingCreature);
# no definition for speak()
}

{ package Mouse;
@ISA = qw(Animal);
sub sound{'squeak'}
sub speak{
my $class = shift;
$class->SUPER::speak(@_);
print "[but you can barely hear it!]\n";
}
}

Mouse->speak('female');

E:\Documents and Settings\Administrator\My Documents\PerlScript>perl perl.pl
a female Mouse goes squeak!
[but you can barely hear it!]

註解:Class->method(@args)或者my $beast= 'Class'; $beast->method(@args)將會構建('Class', @args)引數列表,然後呼叫Class::method('Class',@args);如果沒有發現Class::method,則到@Class::ISA的包中尋找相應method。
$class->SUPER::speak(@_),從當前包的@ISA中對應的包中尋找speak方法,並將($class,@_)傳遞過去

如果將$class->Animal::speak(@_)換成Animal::speak($class, @_)後,因為在Animal中不存在speak方法,所以程式將出錯。而現在的方法在發現Animal中不存在speak方法後將去查詢他的@ISA中包的方法,發現LivingCreature存在speak方法,並呼叫

--------------------------------------------------------------------------------------
開發完一個類之後需要Export,接下來介紹一下相關內容
當輸入use Island::Plotting::Maps qw(load_map scale_map draw_map);

其等價於:
BEGIN{
require Island::Plotting::Maps;
Island::Plotting::Maps->import(qw(load_map scale_map draw_map));
}

這裡的require等價於 require "Island/Plotting/Maps.pm"

接下來利用Exporter的import以Navigate::SeatOfPants為了說明:
package Naviagte::SetOfPants;
use base qw(Exporter);  #包含import方法

our @EXPORT = qw(guess_direction_toward);
our @EXPORT_OK =qw(
get_north_from_professor
according_to_GPS
ask_the_skipper_about
);

our %EXPORT_TAGS = (
all =>  [@EXPORT, @EXPORT_OK],
gps  =>  [qw(according_to_GPS)],
direction  =>  [qw(
get_north_from_professor
according_to_GPS
ask_the_skipper_about
guess_direction_toward
)],
);

@EXPORT表示Navigate::SeatOfPants預設被import的方法,
@EXPORT_OK表示Navigate::SeatOfPants可以被import的方法
%EXPORT_TAG的key表示一組Navigate::SeatOfPants可以被import的方法
use Navigate::SeatOfPants qw(:direction);

當然也可以直接寫import方法,以File::Basename為例:
sub import {
no strict 'refs';
my ($package, $file, $line) = caller;
warn "I was called by $package in $file\n";
for (qw(filename basename fileparse)){
*{$package."::$_"}= \&$_;
}
}
將生成衣呼叫者為字首的函式

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24104518/viewspace-722694/,如需轉載,請註明出處,否則將追究法律責任。

相關文章