Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, folks:

Assumed I have an existing OO module(i.e. Example::Model which might be from other contributors), and I want to add some new methods(not override the existing methods). Besides subclassing, are there any more practical ways to do this from the "design pattern(i.e. GOF)" point of view.

Sample code by subclassing:
package MyApp::Example::Model; use strict; use base 'Example::Model'; sub new { my $class = shift; return bless Example::Model->new(@_), $class; } sub mymethod1 { ####; } sub mymethod2 { ####; } 1;
Thanks a bunch,
Hao Li

Replies are listed 'Best First'.
Re: How to add functions to an existing module?
by ikegami (Patriarch) on Jun 21, 2007 at 01:00 UTC
    Perl doesn't really have a concept of modules. At best, it's a *file* which was required or used. I don't think you want to modify a file. I think you want to modify a package.
    package MyApp::Example::Model; ####; { package Example::Model; sub mymethod1 { ####; } sub mymethod2 { ####; } } ####; 1;

    Note that this will add the methods to all Example::Model objects.

    There is surely a better way of doing what you really want to do.

Re: How to add functions to an existing module?
by GrandFather (Saint) on Jun 21, 2007 at 01:18 UTC

    Consider file noname1.pm containing:

    use strict; use warnings; package noname1; sub new { return bless {}; } 1;

    and noname1.pl containing:

    use strict; use warnings; use noname1; package noname1; sub doit { print "Hello world\n"; } package main; my $obj = noname1->new (); $obj->doit ();

    Executing noname1.pl prints:

    Hello world

    DWIM is Perl's answer to Gödel
Re: How to add functions to an existing module?
by ysth (Canon) on Jun 21, 2007 at 02:44 UTC
    Subclassing should fit the bill. Why do you want to find another solution?

    Unless the superclass (Example::Model, in your example) is poorly written, you shouldn't need to have a sub new in your subclass. Example::Model::new should return a MyApp::Example::Model object when called as MyApp::Example::Model->new().