Perl Function Array Arguement Passing

Hi All,

I have some questions regarding array arguements passing for Perl Function.
If @array contains 2 items , arguements passing would be like Code_A.
But what if @array needs to add in more items, the rest of the code like $_[some number] will have to be modified as well (highlighted in red), which is very troublesome, just like in Code_B where 1 more item is added to @array. Is there an easier way to overcome this problem ?

Code_A

#!/usr/local/bin/perl

my @array = ( "AAA" , "BBB" );


Generic( @array , "WE" , "HIGH" , "DOWN" );


sub Generic {
	foreach my $file ( $_[0] , $_[1] ) {
		print "Now Processing $file ...\n";
	};

	print "$_[2]\n";
	print "$_[3]\n";
	print "$_[4]\n";

}

Code_B

#!/usr/local/bin/perl

my @array = ( "AAA" , "BBB" , "CCC");


Generic( @array , "WE" , "HIGH" , "DOWN" );


sub Generic {
	foreach my $file ( $_[0] , $_[1] , $_[2]) {
		print "Now Processing $file ...\n";
	};

	print "$_[3]\n";
	print "$_[4]\n";
	print "$_[5]\n";

}

There is a couple of ways to tackle the problem. Keep in mind when you pass arguments to a function they all become one big list. So either you pass the strings as the first arguments and the array last:

Generic( "WE" , "HIGH" , "DOWN", @array);
sub Generic {
           my ($w, $h, $d,@t) = @_;
	foreach my $file (@t) {
		print "Now Processing $file ...\n";
	};

	print "$w\n";
	print "$h\n";
	print "$d\n";

}

or you pass a reference to the array (it can be anywhere in the argument list, I place it first here only as an example):

Generic( \@array, "WE" , "HIGH" , "DOWN");
sub Generic {
           my ($ref, $w, $h, $d) = @_;
	foreach my $file (@{$ref}) {
		print "Now Processing $file ...\n";
	};

	print "$w\n";
	print "$h\n";
	print "$d\n";

}

Hi KevinDAC,

Thanks for the advice, but what's the below code trying to do ?
And what does @_ represent ?
And what if there are 2 array list ? Which method would be better ?

my ($w, $h, $d,@t) = @_;

@_ is the automagically created array containing all calling parameters (the array that you use when you access $_[x]). And if there's more than one array to pass around, refs are definitely the way to go, unless you have some other way to discern one array from the other.

Hi pludi,

Thanks for the guidance!
:b: :slight_smile:

I agree with pludi. If you have more than one array, or even really just one array, use references as I showed in my other post. As far as @_ goes, he explained it well enough so I will leave it at that.