Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
If you're looking for a quick and dirty solution and you're working with your own (hash-based) objects this should do the trick:
use strict; use warnings; use Test::More tests => 9; { package root; sub base { "do" } package foo; @foo::ISA = 'root'; sub new { bless {@_[1 .. $#_]}, $_[0] } sub hey { 'yo' } } sub add_method_to_class { my($cls, $name, $meth) = @_; no strict 'refs'; *{"$cls\::$name"} = $meth; } sub add_method_to_obj { my($obj, $name, $meth) = @_; my $class = ref $obj; (my $objcls = "$obj") =~ s/[^A-Z0-9]//ig; { no strict 'refs'; *{"$objcls\::ISA"} = [ @{"$class\::ISA"}, $class ]; } $_[0] = bless { %$obj }, $objcls; add_method_to_class($objcls, $name, $meth); } can_ok foo => 'hey'; can_ok foo => 'base'; eval { foo->new->yay } or pass "foo can't yay"; add_method_to_class('foo', yay => sub { "yay!" }); can_ok foo => 'yay'; my $o = foo->new; eval { $o->woo } or pass "\$o can't woo"; add_method_to_obj($o, woo => sub { "woo!" }); can_ok $o => 'woo'; eval { foo->new->woo } or pass "foo can't woo"; can_ok $o => 'base'; can_ok $o => 'hey';
But if you're looking for a long-term robust solution then follow the sagacious davorg's advice.


In reply to Re: Adding functionality to an Object by broquaint
in thread Adding functionality to an Object by jeanluca

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (2)
    As of 2021-04-16 21:20 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found