eval with parameters

Peter peter at aragos.ru
Sat May 20 12:39:57 BST 2006


>>Hello,
>> 
>> If I need to eval some code string that uses some calling function's 
>> local variables as parameters what syntax should I use?
>> 
>> Case like this:
>> 
>> sub  someFunction {
>> 
>> ($param1,$param2,$codeString) = @_;
>> # $param1 & $param2 - some object or pseudohash variables
>> # $codeString - some external code string that uses $param1 & $param2 as 
>> variables
>> # and returns some value
>> return eval($codeString); }
>> 
>> (I suspect that is stupid question, but I have never do something like 
>> this and I did not find something like this in my manuals yet)


>That's because you almost certainly don't want to do this.

>Step back. Explain what you're trying to achieve.

I have:
1. some $param1, $param2 variables. These variables are objects that contain data & methods
2. some perl code string given from xml configuration. That code returns some value and uses $param1, $param2 data & methods.

Code string may be something like:
$codeString = "if ($param1->someMethods($param2)) {return $param1->{someData};} else {return $param1->{someData};}";

3. I want to eval this code string and let it use $param1 & $param2 data in code like this:

sub someFunction {
my ($param1,$param2,$codeToEval) = @_;
return eval($codeToEval); }

someFunction $param1,$param2,$codeString;

4. This code does not work. Eval is running on $codeString. But when eval calls it uses undef values instead of $param1 & $param2 referenses
:(

5. What is my error in this code? What should I do to allow $codeString eval use $param1 & $param2 values?

}


Peter




More information about the london.pm mailing list