2013-10-30 23 views
1

我已經編寫了下面的代碼,用於將參數傳遞給sample.pl中的eval函數,並在另一個Perl文件sample1.pl中調用該函數。通過在Perl中傳遞參數來調用另一個函數

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! 

可以u人告訴我一個解決方案如何調用一個通過傳遞參數eval的函數

+3

與其說是錯在這裏。 eval用於編譯和運行字符串,不讀取文件並執行它。如果你想在perl中使用反引號執行一個單獨的文件(作爲一個解決方案) – KeepCalmAndCarryOn

+7

讓我們退後一步,考慮一下。你究竟在做什麼?這是一個問題的簡化,還是剛開始學習Perl?你有沒有需要完成的具體任務?請花點時間來解釋你的最終目標是什麼。 – simbabque

+0

除了'@ ISA',你不應該使用'our'。使用'my'!並且使用「$ a」和「$ b」以外的變量作爲'sort'使用的變量。 – ikegami

回答

-1

試試這個這將幫助ü..

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

在接收功能

sub your function name { 
     my ($a,$b) [email protected]_;#these are the arguments 
    } 
+0

以上代碼 – santoshi

+3

如果'$ a'和'$ b'不是整數而是字符串,或者更糟的是,引用? –

8

如何通過傳遞參數來調用通過的eval函數?

sub func { 
    print join(", ", @_), "\n"; 
    return 99; 
} 

my ($str, $a, $b) = ('func', 10, 'tester'); 
my $f = eval "\\&$str" or die [email protected]; 
my $c = $f->($a, $b); 
print "c = $c\n"; 

但有需要使用eval。以上可以寫成

my $f = \&$str; 
my $c = $f->($a, $b); 

甚至

my $c = (\&$str)->($a, $b); 
+1

如果'$ a'和'$ b'不是整數而是字符串,或者更糟糕的參考? –

+0

@ el.pescado,好點,更新了答案 – perreal

+0

或'eval $ str。'($ a,$ b)''本來可以工作(關於el.pescado的觀點)。 – Chris

相關問題