1

我编写了以下代码,用于将参数传递给 sample.pl 中的 eval 函数并在另一个 Perl 文件 sample1.pl 中调用该函数。

样品1.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)}";
 }

样本.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 调用函数

4

2 回答 2

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);
于 2013-10-30T10:52:19.413 回答
0

试试这个这将帮助你..

         my $action="your function name";
         if ($action) {
             eval "&$action($a,$b)";
         }

在接收功能

   sub your function name {
      my ($a,$b) =@_;#these are the arguments 
   }
于 2013-10-30T10:50:36.077 回答