Vijay
Vijay

Reputation: 67311

"Too many arguments" when passing an array to Perl sub?

I have a function below in perl

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

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

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

         }
      }

}

I am calling this function by passing an array argument like below:

create_hash( @files2);

The array has got around 38 values in it. But i am getting compilation errors:

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

what is the wrong that i am doing here?

my perl version is :

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

Upvotes: 27

Views: 22633

Answers (2)

cjm
cjm

Reputation: 62109

Your problem is right here:

sub create_hash()
{

The () is a prototype. In this case, it indicates that create_hash takes no parameters. When you try to pass it some, Perl complains.

It should look like

sub create_hash
{

In general, you should not use prototypes with Perl functions. They aren't like prototypes in most other languages. They do have uses, but that's a fairly advanced topic in Perl.

Upvotes: 82

cdtits
cdtits

Reputation: 1128

May use array reference as:

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

create_hash(\@files2);

Upvotes: -3

Related Questions