Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl passing argument into eval

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

like image 666
ehretf Avatar asked Dec 21 '22 15:12

ehretf


2 Answers

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)
like image 99
ikegami Avatar answered Jan 05 '23 15:01

ikegami


If the string you are evaling 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.

like image 39
amon Avatar answered Jan 05 '23 17:01

amon