There are two three main ways:
  1. Subclassing the module - this lets you add your own methods to the class, and replace or extend methods that are already there.

    Advantage: you write very little code, and your code stays disjoint from the already-existing code.

    Disadvantage: code that needs "your stuff" has to use your new subclass instead of the standard one; if you have code that already uses the old class a lot, you have to go through and change all of the class mentions from the old one to your new one.

  2. Patching the module. There are several ways to go about this (cpan:Sub::Exporter, cpan:Class::AutoPlug, but all of them boil down to manipulating the symbol table to add your new method to the desired namespace.

    Advantage: it looks like you're using bog-standard Module::X, but you get your extension.

    Disadvantage: less understandable to less-experienced programmers. "But magic_method isn't there when I do perldoc Module::X!"

  3. Extending the class by switching namespaces via package, creating the method or methods you want, and returning to your old package.

    Advantage: simpler than the other two. Disadvantage: the package switch needs to occur after the package has been used, but before the method is needed.

    Disadvantage: this adds a execution-order linkage between the module you're extending and the one you extend it in: the module has to be loaded, then your package statement and the sub definition have to be compiled, then after that the method's available. This might get complicated if you do a lot of patching.


In reply to Re: Extend a module by pemungkah
in thread Extend a module by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.