Dear Brethren:

In several places of my module, I need to locally override several methods from another module. One way to achieve this is like this:

sub somesub { no warnings 'redefine'; local *ABC::xyz = sub {1}; # several more # .... }
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 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";
Ideas? Thanks!

  - 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

package Anypackage; sub can_read { # Some checks here }
with
sub can_read { 1 }

In reply to Overriding several methods using 'local' by dmitri

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.