定义 Perl 类的成员函数
其他面向对象的语言有数据安全的概念,以防止程序员直接更改对象数据,并提供访问器方法修改对象数据。Perl 没有私有变量,但我们仍然可以使用辅助方法的概念操作对象数据。
让我们定义一个获取个人姓名的辅助方法 −
sub getFirstName { return $self->{_firstName}; }
另一个设置个人姓名的辅助函数 −
sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; }
现在让我们来看看完整的示例:将“Person”包和辅助函数保留在 Person.pm 文件中。
#!/usr/bin/perl package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print "First Name is $self->{_firstName}\n"; print "Last Name is $self->{_lastName}\n"; print "SSN is $self->{_ssn}\n"; bless $self, $class; return $self; } sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } sub getFirstName { my( $self ) = @_; return $self->{_firstName}; } 1;
现在,让我们如下在 employee.pl 文件中使用 Person 对象 −
#!/usr/bin/perl use Person; $object = new Person( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; # Now Set first name using helper function. $object->setFirstName( "Mohd." ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n";
执行以上程序时,会产生以下结果 −
First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd.
广告