Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

Passing 2D array to a sub()

Hi,

I read a 2d array from file, so I have something like:

    @my2dArray[5][5];

I can iterate over it, ok. I want to pass it to a sub routine, like:

    pass2dArray(my2dArray);

    sub pass2dArray()
    {
        my (@array) = @_;
    }

Am I passing a copy of the 2d array to the function, or is it just referencing the original array?

Then, if I want to pass a single row of the array to another sub, how would I do that? I was hoping something like:

    sub pass2dArray()
    {
        my (@array) = @_;
   
        # pass row 2:
        passOneRowOf2dArray(2);
       
        # etc
        passOneRowOf2dArray(4);
    }

    sub passOneRowOf2dArray()
    {
        my (@row) = @_;
        for (my $i = 0; $i < @row; $i++) {
           ...
        }
    }
   

Thanks
Avatar of Adam314
Adam314

With this:
    pass2dArray(@my2dArray);
You are passing a copy of the original array, which contains references to the 2nd dimension.  You are not passing copies of the 2nd dimension.  Meaning, if your pass2dArray function, if you add or remove elements from @array, this will not be affected in @my2dArray.  But if you change, add or remove elements from any of the rows, this will be affected in @my2dArray.

To pass one row as a reference, you would use:
    passOneRowOf2dArray($array[2]);    #passes reference to second row
To pass one row as an array (not a reference), you would use:
    passOneRowOf2dArray(@{$array[2]});

If you want to pass a copy of a structure like this, you can use the Storable module's dclone function:
http://search.cpan.org/~ams/Storable-2.18/Storable.pm
Avatar of DJ_AM_Juicebox

ASKER

>>To pass one row as a reference, you would use:
    passOneRowOf2dArray($array[2]);    #passes reference to second row


Ok, that's just what I put, but how do you recover the reference to the single row in the function? Like:

    sub passOneRowOf2dArray()
    {
        my @row = shift;
    }

???

That doesn't work though...

Thanks

ASKER CERTIFIED SOLUTION
Avatar of Adam314
Adam314

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This website might be helpful:
http://perldoc.perl.org/perlreftut.html
Perfect, thanks.