TallChuck TallChuck - 7 months ago 12
Perl Question

Using filehandles in Perl to alter actively running code

I've been learning about filehandles in Perl, and I was curious to see if there's a way to alter the source code of a program as it's running. For example, I created a script named "dynamic.pl" which contained the following:

use strict;
use warnings;

open(my $append, ">>", "dynamic.pl");
print $append "print \"It works!!\\n\";\n";


This program adds the line

print "It works!!\n";


to the end of it's own source file, and I hoped that once that line was added, it would then execute and output "It works!!"

Well, it does correctly append the line to the source file, but it doesn't execute it then and there.

So I assume therefore that when perl executes a program that it loads it to memory and runs it from there, but my question is, is there a way to access this loaded version of the program so you can have a program that can alter itself as you run it?

Answer

With a warning about all kinds of issues, you can reload modules.

There are packages for that, for example, Module::Reload. Then you can write code that you intend to change in a module, change the source at runtime, and reload it.

By hand you would delete that from %INC and then require, like

# change source code in the module ...
delete $INC{'ModuleWithCodeToChage.pm'};
require ModuleWithCodeToChange;

The only reason I can think of for doing this is experimentation and play. Otherwise, there are all kinds of concerns with doing something like this, and whatever your goal may be there are other ways to accomplish it.


Note   The question does specify a filehandle. However, I don't see that to be really related to what I see to be the heart of the question, of modifying code at runtime.