How can I redefine Perl class methods?

前端 未结 5 1832
日久生厌
日久生厌 2020-12-30 08:27

The question \"How can I monkey-patch an instance method in Perl?\" got me thinking. Can I dynamically redefine Perl methods? Say I have a class like this one:



        
5条回答
  •  感动是毒
    2020-12-30 08:50

    Not useful in your case but had your class been written in Moose then you can dynamically override methods using its Class::MOP underpinnings....

    {
        package MyClass;
        use Moose;
    
        has 'val' => ( is => 'rw' );
    
        sub get_val {
            my $self = shift;
            return $self->val + 10;
        }
    
    }
    
    my $A = MyClass->new( val => 100 );
    say 'A: before: ', $A->get_val;
    
    $A->meta->remove_method( 'get_val' );
    $A->meta->add_method( 'get_val', sub { $_[0]->val } );
    
    say 'A: after: ', $A->get_val;
    
    my $B = MyClass->new( val => 100 );
    say 'B: after: ', $B->get_val;
    
    # gives u...
    # => A: before: 110
    # => A: after: 100
    # => B: after: 100
    

提交回复
热议问题