分类:
2008-06-20 11:22:26
1. 构造函数是类的子程序,它返回与类名相关的一个引用。将类名与引用相结合称为“祝福”一个对象,因为建立该结合的函数名为bless(),其语法为:
bless YeReference [,classname]
YeReference是对被“祝福”的对象的引用,classname是可选项,指定对象获取方法的包名,其缺省值为当前包名。
创建一个构建函数的方法为返回已与该类结合的内部结构的引用,如:
sub new {
my $this = {};
# Create an anonymous
hash, and
#self points to it.
bless $this;
# Connect the hash to the
local package return $this;
# Return
the reference to the hash.
}
1.
从new()函数返回后,$this引用被销毁,但调用函数保存了对该哈希表的引用,因此该哈希表的引用数不会为零,从而使Perl在内存中保存该哈希表。创建对象可如下调用:
$cup = new
或者可以使用如下的简写:
sub new {
my ($class, $context) = @_;
return bless {}, $class;
}
2. ref($var),如果$var为一个引用,ref函数返回背引用的对象名。如果$var不是一个引用,ref函数返回undef。
3. my $self = {} #创建一个空的匿名hash表的引用
4. my ($class,
$name) = @_;等价于
my $calss = shift;
my $name = shift;
shift 的意思就是把整个 array 的第一个 value 取出,并将 array 长度减一(有点像 pop out)
bless REF,CLASSNAME
This function tells the thingy referenced by REF that it is now an object
in the CLASSNAME package. If CLASSNAME is omitted, the current package
is used. Because a is often the last thing in a constructor,
it returns the reference for convenience. Always use the two-argument
version if a derived class might inherit the function doing the blessing.
See and for more about the blessing (and blessings)
of objects.
Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names. To prevent confusion, you may wish to avoid such package names as well. Make sure that CLASSNAME is a true value.
See .