Perl, a subroutine override with a call to its parent | reference

I am writing a Perl module that will be loaded from the main script. This module uses routines that are defined in the main script (where I am not an maintainer).

For one of the routines, the main script requires an extension, but I do not want to fix the main script. Instead, I want to override the function in my module and save the link to the original routine. If an override is called, I want to call the original subroutine, and then do some extra processing (if required).

character module code

my $referenceToOriginalSub; sub inititialize() { $referenceToOriginalSub = \&originalSub; undef &originalSub; *originalSub = \&overrideSub; } sub overrideSub() { #call original within mainscript &$referenceToOriginalSub(@_); # do some additional processing if required } 

This does not work because it ends with infinite recursion. Obviously, the link to originalSub also points to its substitution.

So, could you point me in the right direction, how to avoid infinite recursion?

+4
source share
1 answer

With the main program

 #! /usr/bin/env perl use strict; use warnings; use MyModule; sub mainsub { print "Original mainsub\n"; } mainsub; 

and with MyModule.pm containing

 package MyModule; use strict; use warnings; my $referenceToOriginalSub; sub overrideSub { print "Override: enter\n"; $referenceToOriginalSub->(@_); # alternative: # goto $referenceToOriginalSub; print "Override: leave\n"; } INIT { no warnings 'redefine'; $referenceToOriginalSub = \&main::mainsub; *main::mainsub = \&overrideSub; } 1; 

The INIT block starts just before the start of your program. This allows use MyModule to come before defining mainsub in the main program and still be able to capture the handle on what is going on under the wind.

You would use goto $referenceToOriginalSub if you are worried about masking side effects in the call stack, but this only allows you to use the execute-before-not-execute-after or execute-around pattern.

Output:

  Override: enter
 Original mainsub
 Override: leave 
+6
source

Source: https://habr.com/ru/post/1499945/


All Articles