How can I redefine Perl class methods?

前端 未结 5 1818
日久生厌
日久生厌 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:41

    You can overwrite methods like get_val from another package like this:

    *{MyClass::get_val} = sub { return $some_cached_value };
    

    If you have a list of method names, you could do something like this:

    my @methods = qw/ foo bar get_val /;
    foreach my $meth ( @methods ) {
        my $method_name = 'MyClass::' . $meth;
        no strict 'refs';
        *{$method_name} = sub { return $some_cached_value };
    }
    

    Is that what you imagine?

提交回复
热议问题