0

I have an issue passing an array and a variable to a function. For example, I have the following.

 my @the_array = ("hello", "hey");
 CallFunction(@the_array, "random")


 sub CallFunction{
     my (@array_ref, $ran_variable) = @_;

     foreach $element (@array_ref){
         print $element ."\n";
     }
 }

I would want the following output

hello
hey

But I get the other variable in the output, and I don't know why.

hello
hey
random
1
  • What you call array_ref is an array, not an array reference. Commented Aug 22, 2014 at 21:35

1 Answer 1

5

The following assignment will put all the values in parameter list @_ into @array_ref:

my (@array_ref, $ran_variable) = @_;

You have two options.

  1. Reorder the passing of parameters, so that the array is at the end:

    my @the_array = ( "hello", "hey" );
    CallFunction( "random", @the_array );
    
    sub CallFunction {
        my ( $ran_variable, @array ) = @_;
    
        for my $element (@array) {
            print $element . "\n";
        }
    }
    
  2. Or pass the array by reference:

    my @the_array = ( "hello", "hey" );
    CallFunction( \@the_array, "random" );
    
    sub CallFunction {
        my ( $arrayref, $ran_variable ) = @_;
    
        for my $element (@$arrayref) {
            print $element . "\n";
        }
    }
    

Minor Note — Naming a normal array @array_ref is a little confusing. Save the ref suffix for variables actually holding references.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.