温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Perl继承的用法

发布时间:2021-07-21 23:36:24 来源:亿速云 阅读:130 作者:chen 栏目:开发技术

本篇内容介绍了“Perl继承的用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Perl继承

类方法通过@ISA数组Perl继承,变量的Perl继承必须明确设定。下例创建两个类Bean.pm和Coffee.pm,其中Coffee.pmPerl继承Bean.pm的一些功能。此例演示如何从基类(或称超类)Perl继承实例变量,其方法为调用基类的构造函数并把自己的实例变量加到新对象中。
Bean.pm代码如下:

packageBean;  requireExporter;  @ISA=qw(Exporter);  @EXPORT=qw(setBeanType);   subnew{  my$type=shift;  my$this={};  $this->{'Bean'}='Colombian';  bless$this,$type;  return$this;  }   #  #Thissubroutinesetstheclassname  subsetBeanType{  my($class,$name)=@_;  $class->{'Bean'}=$name;  print"Setbeanto$name\n";  }  1;

此类中,用$this变量设置一个匿名哈希表,将'Bean'类型设为'Colombian'。方法setBeanType()用于改变'Bean'类型,它使用$class引用获得对对象哈希表的访问。
Coffee.pm代码如下:

1#  2#TheCoffee.pmfiletoillustrateinheritance.  3#  4packageCoffee;  5requireExporter;  6requireBean;  7@ISA=qw(Exporter,Bean);  8@EXPORT=qw(setImports,declareMain,closeMain);  9#  10#setitem  11#  12subsetCoffeeType{  13my($class,$name)=@_;  14$class->{'Coffee'}=$name;  15print"Setcoffeetypeto$name\n";  16}  17#  18#constructor  19#  20subnew{  21my$type=shift;  22my$this=Bean->new();#####<-LOOKHERE!!!####  23$this->{'Coffee'}='Instant';#unlesstoldotherwise  24bless$this,$type;  25return$this;  26}  271;

第6行的requireBean;语句包含了Bean.pm文件和所有相关函数,方法setCoffeeType()用于设置局域变量$class->{'Coffee'}的值。在构造函数new()中,$this指向Bean.pm返回的匿名哈希表的指针,而不是在本地创建一个,下面两个语句分别为创建不同的哈希表从而与Bean.pm构造函数创建的哈希表无关的情况和Perl继承的情况:
my$this={};#非Perl继承
my$this=$theSuperClass->new();#Perl继承

下面代码演示如何调用Perl继承的方法:

1#!/usr/bin/perl  2push(@INC,'pwd');  3useCoffee;  4$cup=newCoffee;  5print"\n--------------------Initialvalues------------\n";  6print"Coffee:$cup->{'Coffee'}\n";  7print"Bean:$cup->{'Bean'}\n";  8print"\n--------------------ChangeBeanType----------\n";  9$cup->setBeanType('Mixed');  10print"BeanTypeisnow$cup->{'Bean'}\n";  11print"\n------------------ChangeCoffeeType----------\n";  12$cup->setCoffeeType('Instant');  13print"Typeofcoffee:$cup->{'Coffee'}\n";

该代码的结果输出如下:

--------------------Initialvalues------------  Coffee:Instant  Bean:Colombian  --------------------ChangeBeanType----------  SetbeantoMixed  BeanTypeisnowMixed  ------------------ChangeCoffeeType----------  SetcoffeetypetoInstant  Typeofcoffee:Instant


上述代码中,先输出对象创建时哈希表中索引为'Bean'和'Coffee'的值,然后调用各成员函数改变值后再输出。

“Perl继承的用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI