in reply to Tied Variables - why?

First off, let it be pointed out that just because a concept is difficult for a beginner does not rule out it's usefullness or power. Objects are not for beginners either. They seem intuitive in the small but they loose that quite quick, as details about classes and inheritance come into play. It's got great syntax as far as organizing the body of your code, but there are lots of details that make it harder to learn to use. This is one of the great advantages of tie: nice syntax without much of that malarky as far as the user goes.

Tied variables are can be very useful and very intuitive. For example take a recent node: Unable to save changes using IO::File. Here is a case where the behavior of the object was not clear but Tie::File would have DWIMed perfectly. The general rule for using a tied variable is when Perl's native syntax fits the problem perfectly, but the underlying implementation does not. Why make an object and have to implement functionality that already exists (like sort for example, or keys) when you don't need to add anything? Why reinvent the wheel? In this sense, tie could be seen as perl's way of inheriting from built in types, but in a very clean and easy way.

And then there are the esoteric uses of tie. Dominus cleverly found a way to extend Memoize's functionality without slowdown or extensive changes to the modules by using tie. This would have been much harder with just objects, not to mention slower, defeating the whole point of having Memoize. Another thought is that, since an object is just a blessed referent, then why not bless a ref to a tied variable? All sorts of nifty magic happens then - for example I am working on a module that would implement Perl 6's accesssor methods syntax in Perl 5. This would not be possible if it weren't for the "weird" and "hard for newbies to understand" features of Perl - source filters, overriding built ins and (you guessed it) tied variables.

One of the things that I love about Perl is that if the core can do it then you can probably do it to, and in pure Perl no less. Have you ever used a special variable in Perl? Liked 'em? Then the beauties of the tie approach should be clear. Ever wanted to implement your own magic variables? Then you need tie.


PS - I'm a bit of a tie evangelist, as you may have noticed. Sorry about that. :-)

Light a man a fire, he's warm for a day. Catch a man on fire, and he's warm for the rest of his life. - Terry Pratchet