[Canberra-pm] Q: Subclassing an object with closures

Alex Satrapa grail at goldweb.com.au
Mon Nov 15 16:36:14 PST 2010


Hello Mongers!

I think I'm going to have to hand in my Perl license, I've encountered a structure I don't understand and now I have no idea how to extend the class.

Observe the contents of the Net::MAC module. There is a closure containing "class data and class methods", so the module basically looks like this:

> package Net::MAC;
> 
> sub new {
>   # Usual blessing a hashref as the class
>   $self->_init(%arg);
>   return $self
>   }
> 
> { # Closure for class data and class methods
>   my %_format_for = (
>     # Hash mapping format name to format options
>     IEEE => {
>       base => 16,
>       bit_group => 8,
>       delimiter => ':',
>       zero_padded => 1,
>       case => 'lower'
>       },
>     )
> }
> 
> sub _discover {
>   # Stuff which handles parsing the MAC string.
>   }

Now what I'd like to do is define a new format or three due to various equipment in my network which produces MAC addresses in formats such as '0xDEADBEEF' which is common in SNMP from what I've seen.

I'd like to take advantage of the existing autoloading, rather than overriding _discover (to take out the 0x where required, then simply invoking the superclass _discover method) and providing an explicitly defined "as_SNMP" method (which simply sticks a 0x on the front).

The first thing I'd like to understand is whether I can add a new entry into that %_format_for hash without touching the Net::MAC module (since I doubt many sysadmins would like my module interfering with read-only modules already installed). Then I'd like to be able to add a new sub into the closure to handle special formatting, such as stripping the 0x off when parsing and adding it on when the user requests as_SNMP.

Of course the simple approach is to create the as_SNMP and override _discover myself, but I can't help feeling that's too easy.

And remember the sage words of H. L. Mencken, "for every complex problem there is a solution which is simple, elegant, and completely wrong."

Alex Satrapa | web.mac.com/alexsatrapa | Ph: +61 4 0770 5332




More information about the Canberra-pm mailing list