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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |