After my article last week regarding Dynamic Method Generation in Perl, here's the conclusion.

See Fun Hacking Perl first unless you've already seen it. It took me a week instead of a day to post this follow up... :-)

Overall, dynamically creating methods can seem like a bit of black magic, some hand waving, smoke and mirrors or all three. But in reality it's fairly straight-forward.

Go take a look at the Class::Accessor module (source) and search for ::$accessor_name (there are 4 instances). It's fairly straight forward and really there are only two steps you have to do:

  1. create an anonymous subroutine (or closure) using sub
  2. inject it into the caller's (being $class} namespace

Of course, there is a few more things you have to be weary of and a few more details to look out for but essentially, that's it.

So far, I now have 5 ways of generating 5 different types of methods. It's kinda cool and means I can remove a lot of template code from http://zaapt.org.nz/ (deprecated) Zaapt.


This post originated on http://chilts.org/.

Email me on andychilton -at- gmail -dot- com.



Published

28 March 2007

Tags