Chinaunix首页 | 论坛 | 博客
  • 博客访问: 318860
  • 博文数量: 88
  • 博客积分: 2051
  • 博客等级: 大尉
  • 技术积分: 950
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-14 23:59
文章分类

全部博文(88)

文章存档

2012年(3)

2011年(2)

2010年(9)

2009年(14)

2008年(60)

我的朋友

分类:

2009-03-03 14:43:50

好多天没学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;

阅读(561) | 评论(0) | 转发(0) |
0

上一篇:生成help文档

下一篇:Perl中的引号

给主人留下些什么吧!~~