dmitri has asked for the wisdom of the Perl Monks concerning the following question:
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 }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Overriding several methods using 'local'
by diotalevi (Canon) on May 22, 2006 at 15:29 UTC | |
|
Re: Overriding several methods using 'local'
by dragonchild (Archbishop) on May 22, 2006 at 15:33 UTC | |
by dmitri (Priest) on May 22, 2006 at 16:10 UTC | |
by dragonchild (Archbishop) on May 22, 2006 at 17:05 UTC | |
|
Re: Overriding several methods using 'local'
by Fletch (Bishop) on May 22, 2006 at 15:56 UTC | |
by dmitri (Priest) on May 22, 2006 at 16:10 UTC | |
|
Re: Overriding several methods using 'local'
by educated_foo (Vicar) on May 22, 2006 at 18:19 UTC | |
by dmitri (Priest) on May 22, 2006 at 18:46 UTC |