在Perl中使用文件句柄来更改正在运行的代码 [英] Using filehandles in Perl to alter actively running code

查看:48
本文介绍了在Perl中使用文件句柄来更改正在运行的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习Perl中的文件句柄,并且很好奇是否有一种方法可以在程序运行时更改其源代码.例如,我创建了一个名为"dynamic.pl"的脚本,其中包含以下内容:

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";

该程序添加行

print "It works!!\n";

到它自己的源文件的结尾,我希望一旦添加了这一行,它便会执行并输出"It work !!"

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.

因此,我因此认为,当perl执行程序时,它会将其加载到内存中并从那里运行,但是我的问题是,是否有一种方法可以访问该加载的程序版本,因此您可以拥有一个可以在运行时改变自身?

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?

推荐答案

在收到有关各种问题的警告后,您可以重新加载模块.

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

有用于此目的的软件包,例如, Module :: Reload .然后,您可以编写要在模块中更改的代码,在运行时更改源,然后重新加载.

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 have it reloaded.

您可以手动将其从%INC中删除,然后从require中删除,例如

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

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

我能想到的唯一原因就是实验和娱乐.否则,这样做会引起各种各样的担忧,无论您的目标是什么,都有其他方法可以实现.

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.

这篇关于在Perl中使用文件句柄来更改正在运行的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆