在销毁中使用Perl类对象变量

时间:2019-02-14 16:52:00

标签: perl

我们可以在perl类的destroy方法内访问对象变量吗? 例如:我有一个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;
}

我如下创建对象:

$object = new Person( "Mohammad", "Saleem", 23234345);

我该如何设置destroy功能,使其像我一样打印

detroying Mohammad

1 个答案:

答案 0 :(得分:3)

与Perl OOP中的所有其他方法一样,DESTROY method的第一个参数具有相同的$self引用。

package Person

sub new { ... }

sub DESTROY {
    my $self = shift;
    print "destroying $self->{_firstName}";
}

package main;
{
    my $foo = Person->new( 'foo', 'bar', 123 );
}

这将打印

First Name is foo
Last Name is bar
SSN is 123
destroying foo