好多天没学Perl了,今天继续开始!
读Perl by Example,这本书很好!
在第二章末尾有个Pet.pm的练习,但是我没细看14章的内容。
package Pet; //声明package,和Java好像类似 # Constructor
sub new { //new用来构造一个对象,必须返回一个引用 my $class = shift; //得到对象的类型 my $pet = { "Name" => undef, "Owner" => undef, "Type" => undef, }; bless($pet, $class); //必须用bless函数来告诉Perl这个$pet就是$class的一个对象,一般情况下,bless是new的最后一个语句,默认就把这个引用$pet返回 # Returns a pointer to the object }
sub set_pet{ # Accessor methods
my $self = shift; my ($name, $owner, $type)= @_; $self->{'Name'} = $name; $self->{'Owner'}= $owner; $self->{'Type'}= $type; }
sub get_pet{ my $self = shift; while(($key,$value)=each(%$self)){ print "$key: $value\n"; } }
1; //最后必须返回真,要不然编译提示错误
|
在另外一个文件中使用刚才写的pm!
BEGIN { //begin在执行perl脚本之前执行 use Pet; //声明用这个模块 die "Error loading libraries:\n$@" if ($@); }
$cat = Pet->new(); # alternative form is: $cat = new Pet();
# Create an object with a constructor method
$cat->set_pet("Sneaky", "Mr. Jones", "Siamese"); # Access the object with an instance
$cat->get_pet;
|
阅读(592) | 评论(0) | 转发(0) |