我编写了以下代码,用于将参数传递给sample.pl中的eval函数,并在另一个Perl文件sample1.pl中调用该函数。
sample1.pl:
use strict;
use warnings;
require 'sample.pl';
use subs "hello";
my $main2 = hello();
sub hello
{
print "Hello World!\n";
our $a=10;
our $b=20;
my $str="sample.pl";
my $xc=eval "sub{$str($a,$b)}";
}
Sample.pl
use strict;
use warnings;
our $a;
our $b;
use subs "hello_world";
my $sdf=hello_world();
sub hello_world($a,$b)
{
print "Hello World!\n";
our $c=$a+$b;
print "This is the called function from sample !\n";
print "C: " .$c;
} 1;
我的输出为:
Illegal character in prototype for main::hello_world : $a,$b at D:/workspace/SamplePerl_project/sample.pl line 6.
Use of uninitialized value $b in addition (+) at D:/workspace/SamplePerl_project/sample.pl line 9.
Use of uninitialized value $a in addition (+) at D:/workspace/SamplePerl_project/sample.pl line 9.
Hello World!
This is the called function from sample !
C: 0Hello World!
你们可以通过传递参数
向我展示如何通过eval调用函数的解决方案答案 0 :(得分:8)
如何通过传递参数来通过eval调用函数?
sub func {
print join(", ", @_), "\n";
return 99;
}
my ($str, $a, $b) = ('func', 10, 'tester');
my $f = eval "\\&$str" or die $@;
my $c = $f->($a, $b);
print "c = $c\n";
但是需要使用eval
。以上可以写成
my $f = \&$str;
my $c = $f->($a, $b);
甚至
my $c = (\&$str)->($a, $b);
答案 1 :(得分:0)
试试这个会帮助你..
my $action="your function name";
if ($action) {
eval "&$action($a,$b)";
}
在接收功能
sub your function name {
my ($a,$b) =@_;#these are the arguments
}