Tie is probably one of the coolest features of modern Perl. The ability to encapsulate complex behaviors as if they were normal Perl datatypes is an enormously powerful idea. It is also enormously easy to abuse.

Here is my litmus test for when to use a tied interface:

Tie is used if you want to fool other code (perhaps not written by you) into doing complex things with what appears to be a normal Perl datatype without that code's knowledge.

Other code should not have to know that a given datatype is tied. If you need more than that, use a full-fledged object system (Perl has plenty of them: bless, Inside out Objects, etc.). Once you've written use Tie::Foo; tie my $data, 'Tie::Foo';, forget you ever wrote those lines until you need to call untie (and you may not need to).

A good use of the tied filehandle interface is GnuPG::Tie::Encrypt (and some of its brethern in the GnuPG namespace). You can pass the filehandle to any bit of code that writes to filehandles, and the data magically comes out the other end as encrypted text.

Tied hashes seem particularly easy to abuse, because it's easy to use them as full method calls. Tie::Google, Tie::Math, and Tie::Sysctl are good (bad) examples of this. They all perform operations that could work better as blessed objects (or whatever other object system you want). At best, they should be in the Acme:: namespace.

So if you're writting a module for tied use, stop to ask if you're better off with a real object.

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

: () { :|:& };:

Note: All code is untested, unless otherwise stated


In reply to When to use Tie by hardburn

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.