Tied Variables: One more reason to love Perl

As many of you know, tied variables lend extra magic to an otherwise normal Perl variable.

One of my favorites comes from File::chdir. This provides your Perl script with $CWD and @CWD. When a folder is assigned to $CWD or pushed onto @CWD the working directory is changed, in a platform independent way. The coolest thing about this is if you first local $CWD, then this change in the working directory is done locally to the block, and is undone as the scope ends.

I just released version 0.03 of Tie::Array::CSV. This module allows accessing a CSV file (or other separator parsable by Text::CSV), using a Perl array.

Underneath the hood there is more tie magic! Tie::Array::CSV uses Tie::File which provides random line access to a file as a Perl array. Using this module in mine allows the module to pick the row just like my users will, as an array index.

Version 0.03 adds a new constructor. So that the users don’t even need to be aware of the tie usage, which looks a little strange at first.

As far as I am aware, other languages don’t have anything like tie. Just one more reason to love Perl! Which other Tie classes do you find especially interesting?

5 Comments

I still haven’t released it to the CPAN, but I’m biased towards Tie::Handle::CountChars

Tie::Hash::Cannabinol

Jokes aside, tie may be convenient but is also very inefficient, and using a tie within a tie is phenomenally so. The feature is very useful for cobbling things together quickly or gluing together things that weren’t designed to be, but it’s one of those tools of last resort.

oooo, that’s rather nice. I might add that to THC (pun intended) though it really doesn’t work with the use-case I had that led me to write it - I was getting handles created by AnyEvent’s tcp_server accept callback and needed to transparently track the number of bytes being read/written as those handles got passed around through a mess of closures, objects, and other sundry code-paths.

I certainly wish I had a more performant way of doing it, but couldn’t figure out anything else that would work simply and reliably. Lucky for me, I didn’t need super-high performance for each connection! :-)

Leave a comment

About Joel Berger

user-pic As I delve into the deeper Perl magic I like to share what I can.