【问题标题】:Calling another function through eval by passing arguments in Perl通过在 Perl 中传递参数通过 eval 调用另一个函数
【发布时间】:2013-10-30 21:41:33
【问题描述】:

我编写了以下代码,用于将参数传递给 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)}";
 }

示例.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 调用函数

【问题讨论】:

  • 这里有很多问题。 eval 用于编译和运行字符串,而不是读取文件并执行它。如果您想在 perl 中执行单独的文件,请使用反引号(作为一种解决方案)
  • 让我们退后一步考虑一下。你到底想做什么?这是对问题的简化,还是您刚刚开始学习 Perl?您是否有需要完成的具体任务?请花点时间解释一下您的最终目标是什么。
  • 你不应该使用our,除了@ISA。使用my!并使用$a$b 以外的变量,因为sort 使用的变量。
  • 除非您是更有经验的 Perl 程序员,否则不要使用 eval。几乎你可以用它做的所有事情都可以通过另一种方式更安全地完成。

标签: perl dynamic


【解决方案1】:

如何通过传参通过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);

【讨论】:

  • 如果$a$b 不是整数而是字符串,或者更糟的是引用怎么办?
  • eval $str.'($a, $b)' 会起作用(关于 el.pescado 的观点)。
  • @Chris,是的,但是 perreal 发布的要好得多。
【解决方案2】:

试试这个对你有帮助..

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

在接收功能中

   sub your function name {
      my ($a,$b) =@_;#these are the arguments 
   }

【讨论】:

  • 如果$a$b 不是整数而是字符串,或者更糟的是引用怎么办?
猜你喜欢
  • 2014-05-05
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2019-02-12
相关资源
最近更新 更多