2012-08-13 100 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