其他面向对象的语言具有数据安全性的概念,以防止程序员直接更改对象数据,并且它们提供访问器方法来修改对象数据。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.