Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a sub being overwritten in Perl?

I'm working with legacy code and have to require a .pl file that defines a sub foo. My problem is that in my main:: namespace there already is another sub foo, which is called later in a part of the program I'm currently not dealing with.

The file I require defines sub foo {} because obviously it does not want the foo things to happen where it is usually called. In my case, that is bad.

I've tried playing around with the *foo glob:

*old_foo = *foo;
require 'foo_killer.pl';
*foo = *old_foo;

Of course, that doesn't work since I've only created an alias (as brian d foy points out on page 133 of Mastering Perl) and thus *old_foo will point to the now 'empty' subroutine.

Is there a way to somehow copy what's in *foo{CODE} to somewhere else instead of aliasing it? Or is there maybe another approach to solve this?

like image 798
simbabque Avatar asked Feb 20 '23 00:02

simbabque


1 Answers

Try like this

{
    local *foo;
    require 'foo_killer.pl';
}
like image 89
PSIAlt Avatar answered Feb 28 '23 11:02

PSIAlt