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

Daniel Pittman daniel at rimspace.net
Mon Nov 15 17:54:50 PST 2010


Alex Satrapa <grail at goldweb.com.au> writes:

> 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.

The goal of a bunch of that code is to make it "private", so that you can't
fiddle with it, so it isn't a great shock that extending it is hard.

> 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).

Absolutely not.  It is by design entirely private, and no longer has a
name-binding by design.

> 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.

You probably need to override _format and _discover to do your mangling,
because the upstream author has deliberately locked you out of being able to
touch the existing method.

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

...is the right solution to fix the module, then submit it to the author, and
just depend on the latest CPAN release?

        Daniel
-- 
✣ Daniel Pittman            ✉ daniel at rimspace.net            ☎ +61 401 155 707
               ♽ made with 100 percent post-consumer electrons


More information about the Canberra-pm mailing list