perl OOP

来源:互联网 发布:淘宝招商的工作好做吗 编辑:程序博客网 时间:2024/05/18 00:37

构造了类的一个对象后,可以使用箭头运算符来调用对象的方法。

objectName ->method(arguments)

 

例如使用FileHandle类

#! /use/bin/perl

#Using the FileHandle module

 

use warnings;

use strict;

use FileHandle;

 

my $write = new FileHandle;

my $read = new FileHandle;

 

$write ->open(">filehandle.txt") or

die("Could not open write");

$read ->open("input.txt") or

die("Could not open write");

 

$write -> autoflash(1);

 

my $i = 1;

 

while (my $line = $read -> getline()){#FileHandle类中的getline()方法

$write -> print($i++," $line");

}

 

 

 

处理日期的类(Date.pm)

 

#!/usr/bin/perl

#A simple Data class

 

package Data;

 

use strict;

use warnings;

 

sub new#定义构造函数,在构造函数里创建散列,散列中容纳了对象数据,并赋默认值

{

my $data = {the_year => 1000, the_month => 1, the_day => 1,};#下面通过bless将散列变成Date对象

bless($data);#bless函数,功能是接受一个引用,并将其转换成对象(perl中所有对象都是引用。当bless接受第二个参数时,就将

#对象变成第二个参数指定的类型。在本例中bless使用了缺省的类型Date。 “bless($date, Date);”

#在调用bless之前打印$date值会输出类似于HASH(0X8BBF0B0)字样,这是打印一个hash引用时典型的输出字符串。如果调用了bless

#后再打印$date会输出date = HASH(0X8BBF0B0)字样,因为$date已经被转换成了一个Date对象。通过“return $data;”返回对象。

return $data;

}

 

sub year

{

my $slef = shift ();#shift方法获得第一个参数

$self -> { the_year } = shift() if (@_);#检查是否有参数传递,如果有,就赋值给散列中的the_year

return $self -> {the_year};#返回属性the_year的值

}

 

sub month

{

my $self = shift();

$self -> { the_month } = shift() if (@_);

return $self -> { the_month };

}

 

sub day

{

my $self = shift();

$self -> { the_day } = shift() if (@_);

return $self -> {the_day};

}

 

sub setData#类似java中的setter getter方法,在这里一次month,year,data赋值

{

if(@_ ==4){

my $self = shift();

$self -> month($_[0]);

$self -> day ($_[1]);

$self -> year ($_[2]);

}

else{

print ("Method setDate requires three arguments./n");

}

}

 

sub print

{

my $self = shift();

print($self -> month);

print ("/");

print ($self -> day);

print ("/");

print ($self -> year);

}

 

return 1;

 

#******************************************测试代码*********************************************

#! /usr/bin/perl

#Using class Date.

 

use Date;

use strict;

use warnings;

 

my $today = new Data;#使用构造方法创建一个Date对象并将其赋值给变量$today

$today -> setDate(7,14,2000);#setDate方法赋值

print($today -> month());#只使用month方法获得month属性

print ("/n");

$today -> print();

print("/n");

原创粉丝点击