Destructors and Garbage Collection in Perl

PERLServer Side ProgrammingProgramming Scripts

If you have programmed using object oriented programming before, then you will be aware of the need to create a destructor to free the memory allocated to the object when you have finished using it. Perl does this automatically for you as soon as the object goes out of scope.

In case you want to implement your destructor, which should take care of closing files or doing some extra processing then you need to define a special method called DESTROY. This method will be called on the object just before Perl frees the memory allocated to it. In all other respects, the DESTROY method is just like any other method, and you can implement whatever logic you want inside this method.

A destructor method is simply a member function (subroutine) named DESTROY, which will be called automatically in following cases −

  • When the object reference's variable goes out of scope.
  • When the object reference's variable is undef-ed.
  • When the script terminates
  • When the perl interpreter terminates

For Example, you can simply put the following method DESTROY in your class −

package MyClass;
   print "MyClass::DESTROY called\n";
Published on 02-Dec-2019 12:13:59