开发者

How can I run dynamic code in Perl?

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")开发者_Python百科 should be executed.


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 abuse eval 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:

 $object->$method(...)

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:

 my @array = ( [ 'r0', 'foo', 'bar' ] );

 foreach my $element ( @array ) {
      my( $identifier, @other_stuff ) = @$element;
      $element->test( $identifier );
      }

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.


You can use eval:

eval($command);

From the manual:

eval EXPR

In the first form, the return value of EXPR is parsed and executed as if it were a little Perl program...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜