user3768541
user3768541

Reputation: 119

perl, function only printing first element of the array

I have an array that has several elements on it but when I pass the array as a parameter to a function and then call the function it only prints out the first element of the array multiple times. For example

my $element;
my $random_variable = "Testing";
my @the_array = ("hello", "bye", "hey");

foreach $element(@the_array)
{
  PrintFunction(@the_array, $random_variable)
}

sub PrintFunction{
 my ($the_array, $random_variable) = @_;
 // other code here

 print $the_array . "\n";

}

The result I get from this is

hello
hello
hello

The result I want is to print all the elements of the array as

hello
bye
hey

Upvotes: 2

Views: 865

Answers (2)

user1709175
user1709175

Reputation:

Add Print @_; to your sub to see what is passed to it. You will see:

hellobyeheyTesting
hellobyeheyTesting
hellobyeheyTesting

It means you are passing the entire array followed by the $random_variable. Therefore, $the_arrayin the sub will be always the first elements of @the_array which is hello. To fix that, you should pass each element of array iteratively by

foreach $element(@the_array)
{
  PrintFunction(@element, $random_variable)
}

Upvotes: 1

toolic
toolic

Reputation: 62037

Change:

  PrintFunction(@the_array, $random_variable)

to:

  PrintFunction($element, $random_variable)

Your code passes the entire array to the sub, then you only print the 1st element of the array each time because you use the scalar variable $the_array inside the sub. Since foreach grabs each element of the array, you probably meant to use $element.

Upvotes: 3

Related Questions