Reload modules

I've got a perl program that runs 24/7, that use subs located in another file. 'require file.sub'.
I wish to be able to change the file.sub, and then make the main program to use the changes, without restarting it.
Is this possible, and how?
Who is Participating?
davorgConnect With a Mentor Commented:
Something like this might work for you:


package Thing;
use strict;
use warnings;
use Exporter;
our @ISA = 'Exporter';
our @EXPORT = 'thing';
no warnings 'redefine';
sub thing {


use strict;
use warnings;
my $time = 0;
while (1) {
  if (!$INC{''} or $time > -M $INC{''}) {
    print "Reloading\n";
    delete $INC{''};
    require Thing;
    $time = -M $INC{''};
  print thing(), "\n";
  sleep 10;

Every 10 seconds it checks the timestamp on and if the module has been changed, it reloads it.

One neat trick - you need to delete the entry from %INC in order for Perl to reload the module.

I am not very sure if this works because I didn't try it.

My idea is to have a signal handler that reloads the module. And whenever you change the file, you just have to send the singal to the program.

Add this to your perl program:
$SIG{USR1} = { sub do "require file.sub"; };

And whenever you change file.sub, just do this at the shell prompt:
kill -USR1 <pid>
where <pid> is the process id of your perl program.

Your program isn't getting restarted but it would just do what you want, it reloads the file.sub

I hope that helps.
Hi PerlKing,
> $SIG{USR1} = { sub do "require file.sub"; };
Might be problematic. I'm not sure what happens if your prog is within your module when you want to replace it.

Check if you need to delete you module's entry from %INC before doing require again.

Zap32Author Commented:
Thanks for all the quick responses.

First I just defined some subs in an other file then the main program, and had the main thing just require the subs. When i tried to use the module called Module::Reload, it said it hade reloaded the file, but when i tried to run the function i had changed, it printed the same ting.
But when I made a module out of the sub, as in your example Dave, it worked :D
I tried to have the 'Thing->import' but that wouldn't work, (looks like it runs the sub it imports ? because it exited the program and told that it couldn't run that function on the object that the sub use.. complicated story... :) ) But when i removed it, it worked..  
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.