http://www.perlmonks.org?node_id=1083580

Theodore has asked for the wisdom of the Perl Monks concerning the following question:

I have seen in Use of %INC ? the answer probably never, and if you do, just for read access to the question when %INC should be used. But I have messed with %INC and I would like to know if there is a better way to do the same thing.

I wanted to be able to redefine a subroutine without restarting the main program process. The subroutine is in a separate .pl file and this specific file is changed: I want to redefine the subroutine with the new file contents without stopping and restarting the main process. In the case of compilation errors in mysub.pl, the main program should not die.

Here is some demo code:

The subroutine file (mysub.pl):

sub mysub { print "foo\n"; }; 1;
The main program:
#!/usr/bin/perl use strict; my $fn = './mysub.pl'; require $fn; while (<STDIN>) { chomp; my $in = $_; if ($in eq 'load') { delete $INC{ $fn }; my $code = "require '$fn'"; eval $code; if ($@) { print "ERROR! Keeping old code.\n"; } else { print "mysub replaced.\n"; }; }; &mysub(); }; exit 0;
Run the main program. Pressing enter, prints "foo". Now, without stopping the main program, change the print statement in mysub.pl to print "bar". Enter 'load' in the main program. After "mysub replaced", "bar" should be printed.

If you omit the delete $INC{ $fn }; line, the subroutine as expected is not redefined. Am I doing something wrong here? Is there a more "mainstream" way to achieve the same thing?

Update: The answer is here: Re: Messing with %INC.