Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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) 
like image 767
Vijay Avatar asked Aug 13 '12 06:08

Vijay


People also ask

How do you pass arguments in Perl subroutine?

Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.

Does Perl pass by value or reference?

Perl always passes by reference. It's just that sometimes the caller passes temporary scalars. Perl passes by reference.


1 Answers

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.

like image 103
cjm Avatar answered Sep 27 '22 21:09

cjm