Perl如何理解和使用OOP中的对象?示例

2021年3月24日14:18:16 发表评论 919 次浏览

Perl是一种面向对象的、动态的、基于解释器的编程语言。在面向对象编程中,我们有三个主要方面,即对象、类和方法。对象是一种数据类型,可以作为其所属类的实例调用。它可以是不同数据类型的数据变量的集合,也可以是不同数据结构的集合。方法是处理类的这些对象的函数。

以下是一个基本示例, 可以更好地了解如何在Perl中使用对象:

第一, 我们需要定义类。在Perl中, 这是通过构建类的包来完成的。包是一个封装的实体, 其中包含有关类的所有数据成员和方法。

package Employee;

在这里, Employee是类名。

第二任务是创建包的实例(即对象)。为此, 我们需要一个构造函数。一种建设者是Perl中的子例程, 通常被赋予名称'新'。但是, 该名称是用户定义的, 因此不限于"新"。

package Employee;
  
# Constructor with name new
sub new 
{
     my $class = shift ;
     my $self = {
                   _serialNum => shift , _firstName => shift , _lastName  => shift , };
      
     bless $self , $class ;
     return $self ;
}

在构造函数中,我们定义了一个简单的散列引用$self来设计对象。这里,该对象将有雇员的三个值serialNum、firstName和lastName,这意味着与此相关的每个雇员都将拥有自己的一组序列号、firstName和lastName。my关键字是一个访问说明符,它将$class和$self本地化到封闭块中。shift关键字从默认数组“@_”获取包名,并将其传递给bless函数。

bless函数用于返回最终成为对象的引用。

最后, 构造函数将最终返回Employee类的实例(此处)。

最后, 主要部分是如何初始化对象。可以通过以下方式完成:

$object = new Employee(1, "Geeks", "forGeeks");

这里, $对象是标量变量, 是对在构造函数中定义的哈希的引用。

以下是在OOP中创建和实现对象的示例程序:

use strict;
use warnings;
  
# class with the name Employee
package Employee;
  
# constructor with the name new
sub new 
{            
     # shift will take package name 
     # and assign it to variable 'class'
     my $class = shift ;    
      
     # defining the hash reference
     my $self = {                         
                 _serialNum => shift , _firstName => shift , _lastName => shift , };
      
     # Attaching object with class
     bless $self , $class ;
      
     # returning the instance of class Employee
     return $self ;                         
}
  
# Object creation of the class
my $object = new Employee(1, "Geeks" , "forGeeks" );
  
# object here is a hash to a reference
print ( "$object->{_firstName} \n" );             
print ( "$object->{_serialNum} \n" );

输出如下:

Geeks 
1

Perl中的对象的工作方式与其他语言(例如C ++, Java等)相同。上面的程序显示了Perl中对象的工作, 其创建以及在类中的使用。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: