perl從5.X版之後也支援OO,不過他不叫object,而是以模組的形式呈現
對於已經習慣java或C#的使用者而言,perl的module應該不大容易上手
下面這段就相當於java的class程式碼
#!/usr/bin/perl
package Mail; //物件名稱
use Mail::Sendmail;
sub new {
my ($class,$mailServer,$user,$passwd,$smtpPort) = @_; //建構子參數,$class代表本身,所以是從mailServer開始塞入參數
my %mail = (
Smtp => $mailServer,
Port => $smtpPort,
Auth => {user => $user, pass => $passwd, method => "LOGIN", required => 1}
);
my $self = {mail => \%mail}; //要public的變數放在這邊,沒有放在這邊的參數就無法使用,hash的話%前面要加上反斜線
bless $self, $class;
return $self;
}
sub sendTo { //物件的function
my ($self,$receiver,$subject,$text) = @_; //參數設定,$self表示自己本身,也就是Mail
my $mail = $self->{mail}; //要讀取本身的public變數用$self->{xxx}
}
將以上這段存成Mail.pm後與主程式放在同目錄,接下來是在程式中去create Mail object
#!/usr/bin/perl
use Mail; //使用剛剛寫的class
$mail = Mail->new('smtpserver','user','passwd','port'); //建構子建立一個mail物件
$mail->sendTo($receiver,$subject,$text); //mail物件的傳送信件function
對於已經習慣java或C#的使用者而言,perl的module應該不大容易上手
下面這段就相當於java的class程式碼
#!/usr/bin/perl
package Mail; //物件名稱
use Mail::Sendmail;
sub new {
my ($class,$mailServer,$user,$passwd,$smtpPort) = @_; //建構子參數,$class代表本身,所以是從mailServer開始塞入參數
my %mail = (
Smtp => $mailServer,
Port => $smtpPort,
Auth => {user => $user, pass => $passwd, method => "LOGIN", required => 1}
);
my $self = {mail => \%mail}; //要public的變數放在這邊,沒有放在這邊的參數就無法使用,hash的話%前面要加上反斜線
bless $self, $class;
return $self;
}
sub sendTo { //物件的function
my ($self,$receiver,$subject,$text) = @_; //參數設定,$self表示自己本身,也就是Mail
my $mail = $self->{mail}; //要讀取本身的public變數用$self->{xxx}
}
將以上這段存成Mail.pm後與主程式放在同目錄,接下來是在程式中去create Mail object
#!/usr/bin/perl
use Mail; //使用剛剛寫的class
$mail = Mail->new('smtpserver','user','passwd','port'); //建構子建立一個mail物件
$mail->sendTo($receiver,$subject,$text); //mail物件的傳送信件function