2012-08-13 40 views
17

我有一個函數低於在Perl將數組傳遞給Perl子時,「參數太多」?

sub create_hash() 
{ 
my @files = @_; 

     foreach(@files){ 
     if(/.text/) 
     { 

     open($files_list{$_},">>$_") || die("This file will not open!"); 

     } 
     } 

} 

我調用這個函數傳遞一個數組參數如下圖所示:

create_hash(@files2); 

數組中它已得到約38的值。 但我得到的編譯錯誤:

Too many arguments for main::create_hash at .... 

什麼是錯了,我現在做的嗎?

我的perl版本是:

This is perl, v5.8.4 built for i86pc-solaris-64int 
(with 36 registered patches, see perl -V for more detail) 
+9

取下'()'? (如'sub create_hash {..}') – 2012-08-13 06:53:41

+0

如果你調用你的函數會發生什麼:create_hash(files2); (不帶「@」符號) – Arfeen 2012-08-13 06:54:38

+0

@ pst如果我刪除它們錯誤是:Array找到操作員預期在process.pl第71行,在行尾 (您需要預先聲明create_hash?) 語法錯誤在進程.pl第71行,在「create_hash @ files2」附近 – Vijay 2012-08-13 06:59:34

回答

53

你的問題就在這裏:

sub create_hash() 
{ 

()prototype。在這種情況下,它表示create_hash不帶參數。當你試圖通過它時,Perl會抱怨。

它應該看起來像

sub create_hash 
{ 

一般來說,you should not use prototypes with Perl functions。它們不像其他大多數語言的原型。他們確實有使用,但在Perl中這是一個相當先進的主題。

+2

上帝保佑。破壞我的頭:) – N3Xg3N 2014-09-05 12:04:36

-3

可能使用陣列基準爲:

sub create_hash { 
    my ($files) = @_; 
    foreach(@{$files)){ 
     ... 
    } 
} 

create_hash(\@files2); 
+0

一* *可以使用array-refs,但它仍然會產生一個錯誤'sub create_hash(){rest_of_that_code}'.. – 2012-08-13 06:59:35

+0

@pst:不是「sub create_hash(){」,它是「 sub create_hash {「 – cdtits 2012-08-13 07:02:40

+2

@cdtits,雖然你的解決方案有效,但是你沒有解釋爲什麼Peter的代碼不起作用。 – cjm 2012-08-13 07:04:33