Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Is there a way to dynamically copy subroutine from one module to another?

by jeffa (Chancellor)
on Feb 12, 2011 at 17:23 UTC ( #887780=note: print w/ replies, xml ) Need Help??


in reply to Is there a way to dynamically copy subroutine from one module to another?

I must admit that the desired output still leaves me puzzled, but you can reach a solution without using aliases, inheritance or possibly even multiple inheritance. Simply pass a D object as an optional parameter to C's doit() method. My solution below uses Moose, i cannot stress how incredibly useful Moose is, especially if you are considering using multiple inheritance (look into roles). Hope this helps. :)

#!/usr/bin/perl -l package A; use Moose; sub doit { warn "A::doit\n" } package B; use Moose; extends 'A'; sub doit { my ($self, $class) = @_; warn "B::doit\n"; return $class ? $class->doit : $self->SUPER::doit; } package C; use Moose; extends 'B'; package D; use Moose; sub doit { warn "D::doit\n" } package main; my $c = C->new; $c->doit( D->new );

output:

B::doit
D::doit

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)


Comment on Re: Is there a way to dynamically copy subroutine from one module to another?
Download Code
Re^2: Is there a way to dynamically copy subroutine from one module to another?
by OlegG (Monk) on Feb 12, 2011 at 18:03 UTC
    In your solution I need to modify B class, but I really can't. Any modifications of classes parent to C will break all. And I can not do this modifications in source code, I need to do it at runtime.

      "Any modifications of classes parent to C will break all."

      If you have a good unit test suite then you should be able to make such a change and find what the change broke elsewhere and correct the problem. I would prefer to correct incorrect code rather than add more incorrect code to fix a symptom.

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://887780]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (16)
As of 2015-07-06 17:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls