Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

A general method of locally overriding subroutines

by tmoertel (Chaplain)
on Mar 11, 2006 at 02:21 UTC ( [id://535859]=perlmeditation: print w/replies, xml ) Need Help??

Help for this page

Select Code to Download


  1. or download this
    use warnings; 
    use strict;
    
    sub a       { "unchanged" };
    sub print_a { print a(), "\n" };
    
  2. or download this
    no strict 'refs';
    no warnings 'redefine';
    ...
        local *a = sub { "changed" };
        print_a();  # prints "changed"
    }
    
  3. or download this
    print_a();      # prints "unchanged"
    
  4. or download this
    sub localize_a_and_call_fn(&@) {
        my ($fn, @args) = @_;
        local *a = sub { "changed" };
        $fn->(@args);
    }
    
  5. or download this
    localize_a_and_call_fn( \&print_a );
    # prints "changed"
    ...
        print "a() => ", a(), "\n";
    };
    # prints "a() => changed"
    
  6. or download this
    sub localize_and_call_fn
    {
    ...
        local *$_ = sub { "changed" } for @$locals;
        $fn->(@args);
    }
    
  7. or download this
    localize_and_call_fn( [qw(a b c)], \&print_a );
    # prints "unchanged"
    
  8. or download this
    #     for (@$locals) {
    #         local *$_ = sub { "changed" };
    #     }
    
  9. or download this
    sub localize_and_call_fn_2
    {
    ...
    
    localize_and_call_fn_2( [qw(a b c)], \&print_a );
    # prints "changed"
    
  10. or download this
    # (sub {
    #     local *c = sub { "changed" };
    ...
    #         })->(@_)
    #     })->(@_)
    # })->();
    

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://535859]
Approved by virtualsue
Front-paged by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 16:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found