user3768541 user3768541 - 7 months ago 4
Perl Question

Passing an array and a variable to a function in Perl

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

Answer

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.

Comments