|Keep It Simple, Stupid|
Now you see it, now you don'tby hardburn (Abbot)
|on May 29, 2003 at 16:29 UTC||Need Help??|
I'd like to start out with a disclaimer. The ideas below are primarily a demonstration of the flexibility of Perl's object system. Using it in a real application is potentially dangerous. I suspect it will have little, if any, benifit for solving real-world problems. It's just a crazy, random idea that managed to escape the bowels of my brain and into the light. I have no idea if it is even truely orginal (really, it's a natural progression of a fairly well-known Perl construct). It won't hurt to learn about it, but then again, many programmers have perfectly happy careers not knowing about Duff's Device.
Many objects use accessors and mutators to provide restricted access to otherwise private data. In Perl, the accessors and mutators are often combined into a single method, like this:
90% of the time, the code for each accessor/mutator is identical to all other accessors/mutators, except for the name of the field. In Perl, there is a shortcut we can use involving closures to generate the accessors/mutators (this snippet is a trimmed-down version of the one on pp. 338-339 of the Blue Camel):
That is cool enough, and cuts out a lot of redundant code. Once I finally understood what was going on here, I was awestruck.
Let's move into a working application of the above:
Run that, and you'll see it print out:
Now remove the 'bah' on line 37 from the list. It will now die when it calls $obj->bah.
Now for the dangerous part. Using closures, we can create and destroy methods at runtime whenever we feel like it.
The second call to $obj->faz() will fail. Crazy, no?
Update: Fixed bug in the example closure where $fields and $slot were in the wrong places (thanks to djantzen for pointing this out).