# Dereferencing a 2D array?!

Hello all,

I'm having a nasty time with the following code:

push @endArray, [\$arrayToSort[\$i][0], \$arrayToSort[\$i][1]];

I'm trying to push the contents of one 2D array into another, one item at a time.  In the above example, I'm trying to do it by (making a fool of myself and) creating a mini-array to push onto @endArray.

The thing is, almost every flavor of what I've tried has given me the ADDRESS of the array item, and not the 2D value of the item itself.  What am I doing wrong?  Do I need to dereference this address?  Is there another way to pass this info??

Thanks,

Raydot.

LVL 3
###### Who is Participating?

Commented:
This is a dereferencing:
@ArrToSort = @\$Level1;

OK,
Let me explain:

You have an array with say, 3 elements

@MainArray = (\$el1,\$el2,\$el3);
They might be simple scalars, holding a number, letter or a string.
Each of them might also be a memory address, pointing to the start of another array.
e.g.
Let's have 3 arrays
@arr1 = ("Elem11","Elem12","Elem13");
@arr2 = ("Elem21","Elem22","Elem23");
@arr3 = ("Elem31","Elem32","Elem33");

How do we put the addresses - pointers of these thee arrays into @MainArray?

Here is how - using referencing:

@MainArray = (\@arr1,\@arr2,\@arr3);

Now if we loop through the first @MainArray and get each element, it will be a memory address internally represented as "ARRAYXX" or something like that. (print it out and check)
So it is not a scalar, but a reference to an ARRAY

we need to take that element (reference) and De-reference it into array. Reference has to be converted back to the original type like this:
@arr1 = @\$MainArray[0];
@arr2 = @\$MainArray[1];
@arr3 = @\$MainArray[2];

And now you can access each element in any array:

print \$arr1[0];
# Would print "Elem11"

print \$arr2[2];
# Would print "Elem23"

And so on.

I hope this clears things out.

0

Commented:

Here is  a demo for you of how to grab your data back.

\$arrayToSort[1][0] = "First Element";
\$arrayToSort[1][1] = "Second Element";

push @endArray, [\$arrayToSort[1][0],\$arrayToSort[1][1]];

foreach \$Level1 (@endArray)
{
@ArrToSort = @\$Level1;
foreach \$Level2 (@ArrToSort)
{
print "\$Level2\n";
};
};

Try it.
0

Author Commented:
Ah...it's not the grabbing back that isn't working, it's the putting in.  The push command itself is no good...

Or wait, no it isn't, I did try it and it worked.  So you're saying the problem was not my push, but my pop?

Could you just break down for me what you're doing with:

@ArrToSort = @\$Level1;

?

Thanks...
0

Author Commented:
Just the answer I was looking for.  If only all respondents were quite this diligent...

Thanks,

Raydot.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.