【问题标题】:"Too many arguments" when passing an array to Perl sub?将数组传递给 Perl 子时“参数太多”?
【发布时间】:2012-08-09 09:27:04
【问题描述】:

我在 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)

【问题讨论】:

  • 脱掉()? (如sub create_hash { .. }
  • 如果你调用你的函数会发生什么:create_hash(files2); (不带“@”符号)
  • @ pst 如果我删除它们错误是: Array found where operator expected at process.pl line 71, at end of line (Do you need to predeclare create_hash?) process.pl line 71的语法错误,靠近“create_hash @files2”
  • 顺便说一句,5.8.4 是一个 真正 古老的 Perl 版本(尽管这与您的问题无关)。你真的应该考虑安装一个更新的版本。 perlbrew 可以提供帮助。
  • 使用 perlbrew,您无需成为管理员即可安装新版本的 Perl 供您自己使用。您只需要一个合适的 C 工具链和足够的磁盘空间。

标签: perl


【解决方案1】:

你的问题就在这里:

sub create_hash()
{

()prototype。在这种情况下,它表示create_hash 不带任何参数。当你试图通过它时,Perl 会抱怨。

应该是这样的

sub create_hash
{

一般来说,you should not use prototypes with Perl functions。它们不像大多数其他语言中的原型。它们确实有用途,但这是 Perl 中相当高级的主题。

【讨论】:

  • 上帝保佑。打破了我的头:)
【解决方案2】:

可以使用数组引用:

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

create_hash(\@files2);

【讨论】:

  • 一个可以使用array-refs,但它仍然会产生sub create_hash() { rest_of_that_code }的错误..
  • @pst: 不是“sub create_hash() {”,而是“sub create_hash {”
  • @cdtits,虽然您的解决方案有效,但您未能解释为什么彼得的代码一开始就不起作用。
  • @cdtits 这就是我的观点——声明不同。切换到数组引用只是次要的:)
  • @pst:那为什么要评论你对数组引用的使用但根本不提及原型设计?
猜你喜欢
  • 2021-03-09
  • 1970-01-01
  • 2019-10-05
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多