In several places of my module, I need to locally override several methods from another module. One way to achieve this is like this:
However, there are several of the subroutines to override in several places of my code. I was wondering if there is a programmatic way of doing this, with a for loop, for example. However, my tests show that it's not possible, since local picks up loop's scope:sub somesub { no warnings 'redefine'; local *ABC::xyz = sub {1}; # several more # .... }
Ideas? Thanks!sub abc { 1 } for my $method (qw(abc)) { local *{$method} = sub { 2 }; } # Prints 1 print abc(), "\n"; if (1) { local *abc = sub { 3 }; } # Prints 1 print abc(), "\n"; eval "local \*{'abc'} = sub { 4 };"; # Prints 1 print abc(), "\n"; local *{$_} = sub { 5 } for ("abc"); # Prints 1 print abc(), "\n"; local *abc = sub { 6 } if 1; # Prints 6 print abc(), "\n";
- Dmitri.
Update 1 in response to dragonchild and Fletch:
I am writing an OO layer of APIs on top of another layer of APIs. The latter is a DB representation and includes access checking here and there buried deep in the hierarchy. I'd like to avoid using those access checks (I have my own), and so I want to replace all instances of things like
withpackage Anypackage; sub can_read { # Some checks here }
sub can_read { 1 }
In reply to Overriding several methods using 'local' by dmitri
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |