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):
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Messing with %INC.
by Anonymous Monk on Apr 24, 2014 at 13:07 UTC | |
by Theodore (Friar) on Apr 24, 2014 at 13:39 UTC | |
by Anonymous Monk on Apr 24, 2014 at 13:44 UTC | |
by Theodore (Friar) on Apr 24, 2014 at 13:51 UTC | |
Re: Messing with %INC.
by mr_mischief (Monsignor) on Apr 24, 2014 at 13:36 UTC | |
by Theodore (Friar) on Apr 24, 2014 at 13:46 UTC | |
by Anonymous Monk on Apr 24, 2014 at 14:15 UTC | |
by Theodore (Friar) on Apr 24, 2014 at 14:38 UTC | |
Re: Messing with %INC.
by Preceptor (Deacon) on Apr 24, 2014 at 14:23 UTC | |
Re: Messing with %INC.
by Anonymous Monk on Apr 24, 2014 at 13:11 UTC | |
by Theodore (Friar) on Apr 24, 2014 at 13:32 UTC |
Back to
Seekers of Perl Wisdom