现在的位置: 首页 > 综合 > 正文

类和对象

2012年03月14日 ⁄ 综合 ⁄ 共 999字 ⁄ 字号 评论关闭

-- Start

Perl 中的类和模块非常相似,都是用包来实现,下面的例子我们定义了一个 Date.pm 类。

#!/usr/bin/perl

# 指定包名,类名和包名相同
package Date;


#------------------------------------------------------- 构造函数
# 构造函数的名字可以是任意的名字,通常使用 new
# 构造函数的第一个参数是类名
sub new {
	my $class = shift(@_); # 得到类名,类名是第一个参数
	my (undef,undef,undef,$d,$m,$y) = localtime(time);

	# 构造一个 hash 的引用, 用来存储 年,月,日
	my $this = {};
	$this->{"year"} = sprintf("%04d", $y + 1900);
	$this->{"month"} = sprintf("%02d", $m + 1);
	$this->{"day"} = sprintf("%02d", $d);

	# 将引用($this)和类($class)关联起来,关联起来后,引用($this)代表该类的一个对象
	bless $this, $class;

	# 返回构造好的对象
	return $this;
}


#------------------------------------------------------- 方法
sub getDate {
	my $this = shift(@_); # 方法的第一个参数是对象的引用
	return $this->{"year"}."-".$this->{"month"}."-".$this->{"day"};
}


# 必须返回一个布尔型的真值,否则 require 时会报错
return 1;

下面的例子演示了如果使用上面定义的 Date 类。

#!/usr/bin/perl

# 使用类
use Date;


# 构造一个Date实例
my $date = Date->new();


# 访问 Date 类中的域
my $year = $date->{"year"};
print "This year is $year\n";


# 访问 Date 类中的函数
my $today = $date->getDate();
print "Today is $today\n";

 

-- 更多参见:Perl 精萃

-- 声 明:转载请注明出处
-- Last Updated on 2012-07-08
-- Written by ShangBo on 2012-07-08
-- End

抱歉!评论已关闭.