I'm facing an issue using eval function.
Indeed I have some function name inside a SQL database, my goal is to execute those functions within perl (after retrieve in SQL).
Here is what I'm doing, considering that $RssSource->{$k}{Proceed} contains "&test" as a string retrieved from SQL:
my $str2 = "ABCD";
eval "$RssSource->{$k}{Proceed}";warn if $@;
sub test
{
my $arg = shift;
print "fct TEST -> ", $row, "\n";
}
This is working correctly and display:
fct TEST ->
However I would like to be able to pass $str2 as an argument to $RssSource->{$k}{Proceed} but I don't know how, every syntax I tried return an error:
eval "$RssSource->{$k}{Proceed}$str2"
eval "$RssSource->{$k}{Proceed}($str2)"
eval "$RssSource->{$k}{Proceed}"$str2
eval "$RssSource->{$k}{Proceed}"($str2)
May someone tell me how to properly pass an argument to the evaluated function?
Thanks a lot for your help
Regards.
Florent
I'm going to assume that $RssSource->{$k}{Proceed}
always contain name
or &name
, otherwise what you are asking doesn't make much sense.
my $func_name = $RssSource->{$k}{Proceed};
$func_name =~ s/&//;
my $func_ref = \&$func_name; # Works with strict on!
$func_ref->(@args);
If you want to add some error checking, the following will check if the sub can be called:
defined(&$func_ref)
If the string you are eval
ing always is a sub invocation, you can construct the eval string in one of these ways:
$RssSource->{$k}{Proceed} . '($str2)'
(most general), or
$RssSource->{$k}{Proceed} . "(\"$str2\")"
(inelegant)
Here are the problems your solutions ran into:
eval "$RssSource->{$k}{Proceed}$str2"
evaluates to eval "&testABCD"
. This sub doesn't exist.
eval "$RssSource->{$k}{Proceed}($str2)"
evaluates to "&test(ABCD)"
. Bareword not allowed.
eval "$RssSource->{$k}{Proceed}"$str2
A string has to be followed by some sort of operator, not another variable.
eval "$RssSource->{$k}{Proceed}"($str2)
You are trying to call a string as a function. This is not supported in Perl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With