[prog] Perl module design

Almut Behrens almut-behrens at gmx.net
Sat Jun 14 00:35:33 EST 2003


On Fri, Jun 13, 2003 at 11:56:01AM +0200, Dan Richter wrote:
> I would like to write a Perl module that uses the HTML::Parser class as a 
> backend but provides different functionality. The HTML::Parser class 
> requires callback functions, either passed as a parameter or in the form of 
> overridden methods in a subclass.
> 
> For me the ideal situation is to have several classes (that do several 
> different things), each of which inherit from HTML::Parser and each of 
> which are used as backends, with the main class used as a frontend. But if 
> I do this, do I have to make separate modules for each class? The classes 
> don't have to be visible to the user, but they do have to be visible to the 
> HTML::Parser class from which they inherit (don't they)? It would be better 
> if I could avoid making separate modules for each sub-class, just because 
> that's extra modules to install.


nothing is holding you back from putting all your classes (i.e.
packages) into one file, if you find it convenient for ease of
installation or whatever... Just put the "package ..." keyword at the
beginning of each section of code that belongs to that particular
namespace -- just as if it were in a seperate .pm-file. In this case,
you, of course, don't need to "use" those modules/classes, because the
code is all there already...

The minimal example below might help to clarify the layout.

Almut



#!/usr/bin/env perl

package My::Test;

sub new {
    my $pkg = shift;
    return bless {}, ref($pkg) || $pkg;
}

sub func {
    print "in My::Test::func()\n";
}

package My::CustomTest1;
use base qw(My::Test);

sub func {
    print "in My::CustomTest1::func()\n";
}

package My::CustomTest2;
use base qw(My::Test);

sub func {
    print "in My::CustomTest2::func()\n";
}

package main;

My::Test->new()->func();
My::CustomTest1->new()->func();
My::CustomTest2->new()->func();



More information about the Programming mailing list