Perl: accessing "my" variables from another file

We have a Perl script that is used for maintenance. I needed to change it to handle more tasks. The problem is that the script was compiled and the source was lost a long time ago.

I tried using B :: Deparse to recreate the file, but Deparse is not perfect and the output is broken (and very large - 5000 lines of dewaxed code).

After reading the dewaxed code, I found that I needed to change one function. The compiled script loads the plain-text script module, so I changed the module to override this function and complete the task I need to complete. The problem is that I can’t access the main script "my" variables.

Here is an example:

# main.pl

my $a = 1;

sub call_me {
    print "unmodified";
}

use MOD;

call_me;


MOD.pm
package MOD;

main::{'call_me'} = sub {
    print "\$main::a = $main::a\n";
}

: "$main::a =" .

.

+5
1

, , my, . "" (- "" script), . Perl .

PadWalker - ( )

main.pl script:

my $a = 1;

sub call_me {
    print "unmodified: $a";
}

use MOD;

call_me;

:

package MOD;

# closed_over($code_ref) returns a hash ref keyed on variable
# name(including sigil) with values as references to the value
# of those variables
use PadWalker qw(closed_over);

{
    # grab a reference to the original sub
    my $orig = \&main::call_me;

    # no need to use the symbol table, a glob reference is fine
    # but you can't use sub main::call_me { ... } either
    *main::call_me = sub {
        my $a = closed_over($orig)->{'$a'};
        print "\$main::a = $$a\n";
    }
}
+8

All Articles