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

Hi , I am very new to perl & started developing a small tool for text analysis. I like to make a subroutine to return a 3 D array to main code.psuedu code is ..
sub multi() { @a1; @a2=\@a1; @a3=\@a2; Assigned values to a3[$i][$j][$k] // when i print a3 all the ranges of i,j,k its printing good. return \@a3; } my @arrMain = multi();
I like to get the same values here too . when i say a3[0][2][1] i should get the element

Similarly i should pass a 3D array to a subroutine & get the retun 3 d array.

It looks like a simple but i am looking for help.... if any one can ..

Thanks in advance vel

Replies are listed 'Best First'.
Re: Returning Multidimensional array from subroutine to main code
by Athanasius (Archbishop) on Oct 19, 2013 at 03:26 UTC

    Hello vels, and welcome to the Monastery!

    Here is some simple code to create a 3D array, pass it into and out of a subroutine, and print it using the module Data::Dump:

    #! perl use strict; use warnings; use Data::Dump; my @array3d = ( [ [ 'a', 'c', 'e', ], [ 'f', 'h', 'j', ], [ 'k', 'm', 'o', ], ], [ [ 'A', 'C', 'E', ], [ 'F', 'H', 'J', ], [ 'K', 'M', 'O', ], ], ); dd \@array3d; my $array_ref = multi(\@array3d); dd $array_ref; print "$array_ref->[0][2][1]\n"; $array_ref->[0][2][1] = 'Change 2'; dd $array_ref; sub multi { my ($array3d_ref) = @_; $array3d_ref->[1][1][2] = 'Change 1'; return $array3d_ref; }

    Output:

    13:12 >perl 749_SoPW.pl [ [["a", "c", "e"], ["f", "h", "j"], ["k", "m", "o"]], [["A", "C", "E"], ["F", "H", "J"], ["K", "M", "O"]], ] [ [["a", "c", "e"], ["f", "h", "j"], ["k", "m", "o"]], [["A", "C", "E"], ["F", "H", "Change 1"], ["K", "M", "O"]], ] m [ [["a", "c", "e"], ["f", "h", "j"], ["k", "Change 2", "o"]], [["A", "C", "E"], ["F", "H", "Change 1"], ["K", "M", "O"]], ] 13:12 >

    Note the -> in the expression $array3d_ref->[1][1][2]. This is required; see:

    Also, please put your code within <code> ... </code> tags, as this makes it easier for the monks to read.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Returning Multidimensional array from subroutine to main code ;
by marinersk (Priest) on Oct 19, 2013 at 05:24 UTC
    I would pass the array by reference. As an added bonus, you don't have to return it, as the subroutine will update the original array directly. (This is not always a good thing but probably is desired here.)

    Example:

    my @array = (); # ... populate array here &multi(\@array); # ... later, the subroutine: sub multi { my $arrayReference = shift; my @localArray = @$arrayReference; # ... do stuff to @localArray # ... it actually affects the original array }

    A more full demonstration is hidden behind the readmoretag: