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):
The main program:sub mysub { print "foo\n"; }; 1;
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.#!/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;
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.In reply to Messing with %INC. by Theodore
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |