How can I redefine Perl class methods?

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

    How do I modify to just do this?:

    cache_fn(\&myfn);

    Well based on your current example you could do something like this....

    sub cache_fn2 {
        my $fn_name = shift;
        no strict 'refs';
        no warnings 'redefine';
    
        my $cache_value = &{ $fn_name };
        *{ $fn_name } = sub { $cache_value };
    }
    
    cache_fn2( 'myfn' );
    

    However looking at this example I can't help thinking that you could use Memoize instead?

提交回复
热议问题