[Israel.pm] Perl construct that I liked

Shmuel Fomberg semuelf at 012.net.il
Thu Feb 8 09:06:24 PST 2007


Hello There.

Another construct that I liked was AutoSubs. And to use it I defined a
package:

Package AutoSub;
sub DESTROY { &{$_[0]}; }

(It's from the memory, so there may be a typo)

now, suppose I have a function A that need to do cleanup, but want to
leave the "when" question to the programmer, I do:
sub A {
   ... Do work ..
   $cleanup_sub = sub {
      ... do cleanup ...
   };
   return bless $cleanup_sub, 'AutoSub';
}

now the programmer just have to hold the reference that he got for as
long as he needs, and then the subroutine will detonate by itself.
If A decide that no cleanup is needed, it can return undef, and the
programmer don't need to check or something. Just to continue hold the
pointer (that is undef, but he shouldn't care) until the cleanup time.
(that won't happen, but again, why should he care?)

Good night,
Shmuel.





More information about the Perl mailing list