The guiding principle is simple: DESTROY should clean up whatever doesn't get cleaned up automatically when the object is deleted.

Example:

One of the nice things about perl is that object destruction is predictable. Simply put, if an object goes out of scope, or is otherwise unreachable, it gets destroyed before the rest of the code is executed. This also means you can also (ab)use DESTROY to do all kinds of "magical"/intuitive things with relatively few headaches.

Languages like Java only destroy unreachable objects "when they feel like it" - usually when they run out of memory or some other limit is reached. That means that in Java it's a bad idea to rely on object destruction to close filehandles or sockets - you can run out of available file handles or other resources before the objects get destroyed. In perl this kind of usage is fairly common.

The nasty thing about this predictability is that object destruction/garbage collection is done via reference counting. That means that if object a has a reference to object b and vice versa and both objects are otherwise unreachable neither object is deleted.

One way of dealing with this is to make one of the references a weak reference (see Scalar::Util's weaken() function).

Another way is to have a "guardian" object keep reference to both object a and b and at its destruction break the circular references between the objects. DESTROY is typically used for that.


In reply to Re: What _should_ DESTROY do? by Joost
in thread What _should_ DESTROY do? by dokkeldepper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.