加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl OOP

发布时间:2020-12-15 23:41:58 所属栏目:大数据 来源:网络整理
导读:1. 模块/类(包) 创建一个名为Apple.pm的包文件(扩展名pm是包的缺省扩展名,意为Perl Module)。 一个模块就是一个类(包)。 2. new方法 new()方法是创建对象时必须被调用的,它是对象的构造函数。 sub new { my $class = shift ; my $this = {}; bless $this ,

1. 模块/类(包)

创建一个名为Apple.pm的包文件(扩展名pm是包的缺省扩展名,意为Perl Module)。
一个模块就是一个类(包)。

2. new方法

new()方法是创建对象时必须被调用的,它是对象的构造函数。

sub new {
    my $class = shift;
    my $this = {};
    bless $this,$class;
    return $this;
}

this={}/ this。
bless()函数将类名与引用相关联。从new()函数返回后,$this引用被销毁。

3. bless方法

构造函数是类的子程序,它返回与类名相关的一个引用。
bless()函数将类名与引用相关联。
其语法为:bless reference [,class]
reference: 对象的引用
class: 是可选项,指定对象获取方法的包名,缺省值为当前包名。

4. 类方法

有两种方法:静态方法(如:构造函数)和虚方法。
静态方法第一个参数为类名,虚方法第一个参数为对象的引用。
虚方法通常首先把第一个参数shift到变量self或this中,然后将该值作普通的引用使用。
静态方法直接使用类名来调用,虚方法通过该对象的引用来调用。

5. 继承

@ISA数组含有类(包)名,@INC数组含有文件路径。
当一个方法在当前包中未找到时,就到@ISA中去寻找。
@ISA中还含有当前类继承的基类。

类中调用的所有方法必须属于同一个类或@ISA数组定义的基类。
@ISA中的每个元素都是一个其它类(包)的名字。
当类找不到方法时,它会从 @ISA 数组中依次寻找(深度优先)。
类通过访问@ISA来知道哪些类是它的基类。
e.g.

use Fruit;
our @ISA = qw(Fruit);

6. OOP Sample

Super Class: Fruit.pm

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

package Fruit;

sub prompt {
    print "nFruit is good for healthn";
}

1;

Sub Class: Apple.pm
Note: Sub class Apple.pm extends super class Fruit.pm via putting Fruit into array @ISA in Apple.pm

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

package Apple;

use Fruit;
our @ISA = qw(Fruit);

sub new {
    my $class = shift;
    my %parm = @_;

    my $this = {};

    $this -> {'name'} = $parm{'name'};
    $this -> {'weight'} = $parm{'weight'};

    bless $this,$class;

    $this -> init();

    return $this;
}

sub init {
    my $reference = shift;
    my $class = ref $reference;

    print "class: $classn";

    while (my ($key,$value) = each (%$reference))
    {
        print "$key = $valuen";
    }
}

sub order {
    my $class = ref shift;
    my $customer = shift;
    my $address = shift;
    my $count = shift;

    print "n$customer order $count $class to $addressn";
}

1;

Main Class: Purchase.pl

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

use Apple;

my $apple = new Apple('name' => 'Red Fuji','weight' => 300);

$apple -> prompt();

$apple -> order('Zhou Shengshuai','ChengDu',99);

Output:

class: Apple
weight = 300
name = Red Fuji

Fruit is good for health

Zhou Shengshuai order 99 Apple to ChengDu

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读