Hello wise monks,

I am trying to figure how to replace object methods at runtime. Does it exist symbol table per object(instance) or only per class/package? My simple test case is this:
#!/usr/bin/perl { package foo; sub new { my $type = shift; return bless {}, $type; } sub baz { print "foo-baz\n"; } sub m { my $self = shift; # do some init here print "replace\n"; *m = sub { $self->baz }; $self->m(); } } { package bar; use base foo; sub baz { print "bar-baz\n"; } } # main my $x = new foo; my $y = new bar; $x->m; $y->m;
When executed it produces:
replace foo-baz foo-baz
It is clear that the line:
*m = sub { $self->baz }
replaces the sumbol entry in the class/package but not in the working instance/object.
If I have written
*m = sub { my $self = shift; $self->baz }
then the correct method baz will be called but the method "m" will be replaced only once.
Is there any hope to do this with symtable manipulation?
The current solution is to make a dispatch table per instance and manipulate its entries. I do not like it. The method invocation syntax now is :
$self->{m}->($self,@args);
But if I could skip this level of indirection I will be happy.

Thanks in advance

In reply to 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.