2013-11-21 79 views
2

我想從我的perl腳本(sample1.pl)調用另一個perl腳本(sample.pl)中有8個參數的子例程。 我收到此錯誤。 錯誤顯示爲如何調用另一個perl腳本中有8個參數的子例程

"sum of 8 numbers is 0Illegal character in prototype for main::callng_prgm : $a,$b,$c,$d,$e,$f,$g,$h at D:/workspace/sdff/sample.pl line 4. 
Use of uninitialized value $b in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $a in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $c in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $d in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $e in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $f in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $g in addition (+) at D:/workspace/sdff/sample.pl line 6. 
Use of uninitialized value $h in addition (+) at D:/workspace/sdff/sample.pl line 6. 
" 

可以請你建議我如何做到這一點

sample1.pl

require 'sample.pl'; 
use strict; 
use warnings; 
my $sa = main_prgm(); 
sub main_prgm { 
    eval(callng_prgm(10,12,15,14,16,12,12,12)); 
} 

sample.pl

use strict; 
use warnings; 
our ($a,$b,$c,$d,$e,$f,$g,$h); 
sub callng_prgm ($a, $b, $c, $d, $e, $f, $g, $h) { 
    my $z = ($a+$b+$c+$d+$e+$f+$g+$h); 
    print "sum of 8 numbers is $z"; 
} 
1; 
+3

Perl中的原型不是必需的,並且不像其他語言那樣工作,所以除非你知道他們做了什麼,否則不要使用它們。 (原型是包含在子名稱後面的parens)。一個子聲明應該是這樣的:'sub NAME {CODE}'(沒有parens) – TLP

+1

您嘗試使用在perl5中未實現的命名參數您可以通過另一種方式實現http://perldesignpatterns.com/?NamedArguments – teodozjan

回答

1

只需定義你的子類:

sub callng_prgm 
{ 
    my ($a,$b,$c,$d,$e,$f,$g,$h) = @_ 
    my $z= ($a+$b+$c+$d+$e+$f+$g+$h); 
    print "sum of 8 numbers is $z"; 
} 
+0

是的,我正在使用該代碼,它給出了答案,但有一個警告,因爲「主要的:: callng_prgm原型中的非法字符:$ a,$ b,$ c,$ d,$ e,$ f,$ g,$ h at D:/workspace/sdff/sample.pl第4行「,如何解決該警告.. –

+2

@santoshikumari不,你沒有使用該代碼,或者你不會得到該警告。這是完全不可能的,所以請仔細閱讀M42發佈的代碼。 – TLP

+0

謝謝......它的工作 –

1

爲什麼限制自己8個參數?這將適用於任何數量的參數。

#!/usr/bin/perl 

use strict; 
use warnings; 
sub callng_prgm 
{ 
    my $z; 
    foreach (@_) {$z += $_}; 
    print $z; 
} 
callng_prgm(10,12,15,14,16,12,12,12); 
相關問題