1. Perl
  2. Syntax
  3. here

Destructor - DESTROY

Perl is a programming language with reference counting GC. The object is freed when the reference count reaches zero.

By implementing a method called DESTROY, the destructor can be executed when the reference count reaches 0.

sub DESTROY {
  # What happens when an object is released
  ...
}

Close the file handle with a destructor

For example, suppose you have a File class that represents a file. The File class stores the file handle opened by open function in the fh field.

Suppose you want to close this using close function when you open the object.

In such a case, write the destructor as follows:

package File;
use Carp 'croak';

# Constructor
sub new {
  my ($class, $file) = @_;
  
  my $self = {};
  open my $fh, '<', $file
    or croak "Can't open $file:$!";
  $self->{fh} = $fh;
  
  return bless $self, $class;
}

# Destructor
sub DESTROY {
  my $self = shift;
  print "DESTROY";
  close $self->{fh};
}

package main;

{
  my $file = File->new('a.txt');
}

Reference: Object Oriented, Carp Module, Scope, main package

When I run this script, it says "DESTROY", which I put in to make sure the destructor is running. The destructor is running and the file handle is closed.

Main uses of destructors

Destructors are often used when closing external resources such as files and databases. Since Perl has a clear timing for the object to be released, you can write the resource closing process in the destructor.

Related Informatrion