Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

First of all, please excuse my perl ignorance, I am just starting out! I want to build an array of arrays in one function, return it, store it in a variable and then pass it into another function to print it's contents. Everything is declared as 'my'. When I print the results all the array elements seem to contain what was the last value entered. Is there anything special I need to consider when passing an array of arrays? Could I be encountering a problem of scope?

Replies are listed 'Best First'.
Re: Passing arrays
by jasonk (Parson) on Mar 10, 2003 at 17:31 UTC

    There are many things you could be encountering, since you didn't post any code we will have to consult the oracle to determine what the nature of your problem is:

    The oracle says: "Lightning strikes."

    # store the array in a variable my @foo = builder(); # pass it to another function to print the contents printer(@foo); # build array of arrays (sic) and return it sub builder { my @built = ( [qw/a b c d e f g/], [qw/1 2 3 4 5 6 7/], ); return @built; } # print the data sub printer { my @array = @_; foreach(@array) { print join(' ',@{$_})."\n"; } } __DATA__ a b c d e f g 1 2 3 4 5 6 7
      In the interest of TMTOWTDI and as a newbie as well, I also like this approach for displaying without the join:
      # print the data sub printer { my @array = @_; foreach(@array) { print "@{$_}\n"; } }
Re: Passing arrays
by meetraz (Hermit) on Mar 10, 2003 at 17:30 UTC
    Try this:

    use strict; my $AofA = buildAofA(); display_AofA($AofA); sub buildAofA { my $AofA = [ [qw( one two three four )], [qw( five six seven eight )], [qw( nine ten eleven )], ]; return $AofA; } sub display_AofA { my $AofA = shift; foreach my $array (@$AofA) { print join(',',@$array), "\n"; } }
Re: Passing arrays
by nadadogg (Acolyte) on Mar 10, 2003 at 20:29 UTC
    Well, I had to do something similar to this recently. This is the code that i used to read my input from a file into an array or arrays, aka a matrix. This was the subroutine to put it into a matrix, which other subs then moved about, ultimately putting into another file. Hope it helps some.
    open FILE, "<input.txt"; open OUTP, ">output.txt"; undef (@matrix); while (<FILE>){ push @matrix, [split]; } &dataconvert; # this is where it branched off to #change up the data select OUTP; for $i (0.. ($#matrix)){ print "@{$matrix[$i]} \n"; }
    It simply pushed the contents of the file into a matrix using push. I hope this helps you out a bit.