Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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

by ig (Vicar)
on Aug 05, 2012 at 19:20 UTC ( #985566=note: print w/ replies, xml ) Need Help??


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; }


Comment on Re: Question about how to return a array in subroutine to form a two dimensional array
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985566]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2014-07-28 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (193 votes), past polls