Kasper Kasper - 7 months ago 13
Perl Question

Passing array in Perl

I have this currently working:

sub first_sub
{
my @my_array;

## The second sub will return my_array filled out!
second_sub (\@my_array);

## Array ok ... filled out!
}


But what about if I want/need to pass the array from second_sub to another subroutine? For example:

sub first_sub
{
my @my_array;

## The second sub will return my_array filled out!
second_sub (\@my_array);
## ...
}

sub second_sub
{
my $my_array = shift;

## The second sub will return my_array filled out!
second_sub (my_array); ## Passed by value ...

## Array empty here (because passed by value, right?) !!!
}

Answer

Once you have an array reference in a scalar variable you can pass it between subroutines as you wish.

Your example code is badly broken, but I assume you mean something like this:

first_sub();

sub first_sub {
    my @my_array;

    ## second_sub will fill out @my_array

    second_sub (\@my_array);   ## Passed by reference

    print join(', ', @my_array), "\n";
}

sub second_sub {
    my ($my_array) = @_;     ## Received by reference

    ## third_sub will fill out @my_array

    third_sub ($my_array);   ## Passed by reference
}

sub third_sub {
    my ($my_array) = @_;     ## Received by reference

    @$my_array = qw/ a b c d e /;
}

Output

a, b, c, d, e