http://www.perlmonks.org?node_id=985566


in reply to Question about how to return a array in subroutine to form a two dimensional array

Your immediate issue seems to be:

$arr[$index] = @$arr_ref;

@$arr_ref is the array returned by your subroutine. Evaluated in scalar context, it yields the number of elements in the array: 101.

An array element cannot hold an array, but it can hold an array reference and your subroutine returns an array reference. If you change the line to:

$arr[$index] = $arr_ref;

You may have something more like what you were hoping for. You will certainly have some output other than newlines.

When trying to discover why my data structures are not what I want or expect, I find Data::Dumper very helpful. In the case of your program, the following might help you:

use Data::Dumper; sub sub1{ for $x (0 .. 100){ $array[$x] = 0; } # omit the part for generating the array; return \@array; } ####################### main part my $index; for ($index=0; $index<2; $index++){ $arr_ref = &sub1($index); $arr[$index] = @$arr_ref; die Dumper(\@arr); foreach (0 .. 100){ print "$arr[$index][$_]\n"; } }

This gives the following output:

$VAR1 = [ 101 ];

You need to get familiar with Data::Dumper to understand this output, but it is Perl code. This shows that @arr was an array of one element having the value 101. Try removing the '@' as I suggested and see what you get.

I note also that your subroutine is using the global array @array. Each time it runs it sets values in that array and returns a reference to it. As it is the same array each time, each reference is a reference to the same array. They are not independent, as you may be expecting.

There are various ways you could return a unique array form each execution of your subroutine. I would probably do something like the following:

sub sub1{ my @array; for $x (0 .. 100){ $array[$x] = 0; } # omit the part for generating the array; return \@array; }