You can't replace methods per-object, only per class or package. So instead, how about replacing the object's class! Let's assume that you want to replace the foo method in $object ...
use Scalar::Util qw(refaddr); my $newclass = q[ package $CLASS::FakeClass$OBJID; use base qw($CLASS); sub foo { my $self = shift; ... blah blah blah ... } ]; $newclass =~ s/\$CLASS/ref($object)/eg; $newclass =~ s/\$OBJID/refaddr($object}/eg; eval $newclass; bless $object, ref($object)."::FakeClass".refaddr($object);
That creates a new class just for that object (the one-to-one class-to-object correspondence is guaranteed by using the object's address in memory as part of the class name), which inherits from the class that the object is already an instance of, then reblesses it. Any methods defined in the new class will override those in the original class, and any others will just be passed through to the original class in the usual way.

The one problem with this is that you'll need to be really careful if you serialise and later unserialise objects. In particular, objects are extremely unlikely to be unserialised at the same address in memory, which may lead to later namespace clashes.

Code is untested, but I do something similar quite often, so the principle is correct even if I typed it wrong :-)


In reply to Re: replace object methods at runtime by DrHyde
in thread replace object methods at runtime by karavelov

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.