如何在 Perl 中运行动态代码?
我有一个关于 Perl 动态代码的问题。 Perl 中是否有一个构造可以用来执行代码。
例如,
$command = " some command";
$perl -> execute($command);
$command
在运行时发生变化。抱歉我的术语。否则我不知道如何解释。
我试图实现这一点:我有一个函数,可以为数组中的每个引用执行一些命令。
...insert example call to function...
假设每个引用都有一个关联的标识符。
...insert sample reference...
...say something about how you determine the identifier...
...say something about how you want to use the identifier...
我无法迭代数组并对每个引用执行,因为命令的一部分因每个引用而异,因为它具有标识符的一部分,并且没有详尽的标识符列表。例如,如果 $r0
具有标识符“r0”,则应执行命令 $r0->test("r0")
。
I have a question relating to Perl dynamic code. Is there a construct in Perl where I could use to execute code.
For instance,
$command = " some command";
$perl -> execute($command);
$command
changes in run time . Sorry for my terminology. I do not know how to explain it otherwise.
I am trying to accomplish this: I have a function which execute some command for each reference in a array.
...insert example call to function...
Let's say each reference has an identifier associated.
...insert sample reference...
...say something about how you determine the identifier...
...say something about how you want to use the identifier...
I can't iterate through the array and execute for every reference since a portion of the command varies for each reference as it has a part of the identifier and there is no exhaustive list of identifiers. For instance if $r0
has an identifier 'r0', the command $r0->test("r0")
should be executed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这是一个外部命令,您可以使用系统、反引号或 Perl 模块之一来完成此类操作。
如果你想在运行时编译并执行Perl代码,你可以使用
eval
。在许多情况下,人们滥用eval
因为他们看不到更简单的方法来完成工作。如果你想根据情况决定运行哪个子例程,你可以做各种事情,包括使用软引用(讨厌!但有时很有用)、调度表等等。
如果您想根据变量中的值选择一种方法,这也很容易:
但是,您必须告诉我们您想要完成什么。
我仍然不确定你在问什么,但这听起来并不像任何动态的东西。我想这就是你所描述的情况。告诉我这有多接近:
如果您可以显示一些示例元素和更完整的(即使是伪代码)概述您所拥有的内容,那将会非常有帮助。我们只知道您在问题中告诉我们的内容,而不是您对自己问题的所有了解。
If this is an external command, you can use one of
system
, backticks, or a Perl module for that sort of thing.If you want to compile and execute Perl code at run time, you can use
eval
. In many cases, people abuseeval
because they don't see the simpler way to get things done.If you want to decide which subroutine to run based on the situation, you can do various things, including using soft references (ick!, but useful sometimes), dispatch tables, and so on.
If you want to choose a method based on the value in a variable, that's easy too:
However, you'd have to tell us what you are trying to accomplish.
I'm still not sure what you are asking, but it doesn't really sound like anything dynamic. I think this is the situation you are describing. Tell me how close this is:
It would really help if you can show some sample elements and a more complete, if even pseudo code, outline of what you have. We only know what you tell us in your question, not everything you know about your own problem.
您可以使用
eval
:来自 手册:
You can use
eval
:From the manual: