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

I may be having some trouble with terminology here, so please bear with me. I need to dereference (I think that is the correct term) a data structure. Let’s say I create this array:
@array = (1,2,3,4,5,6,7,8);
Now, I also have an array reference that looks like this:
@{$arrayref} = (1,2,3,4,5,6,7,8);
I can say:
@array2 = @{$arrayref};
And now @array2 should be identical to @array and it appears, through limited testing, that it is. But will this work for an array of arrays or an array of hashes or hashes of arrays and so on and so forth? Or is there a better way to accomplish this type of task?

Replies are listed 'Best First'.
Re: Dereferencing of data
by diotalevi (Canon) on Oct 09, 2003 at 17:57 UTC
    @new_array = @$array;

    That's a shallow clone of an array reference. For deep cloning use Storable.

Re: Dereferencing of data
by revdiablo (Prior) on Oct 09, 2003 at 17:32 UTC
    @array2 = @{$arrayref};

    This will copy the referenced array into a new array. Usually when we speak of dereferencing, we mean using a reference directly (e.g. $arrayref->[2]). That aside, this will give you a "real" array from a reference, with the caveat that it will be making a copy, and might potentially be very expensive. I really recommend just using the reference directly.

      Thanks for the clarification on the terminology.

      Is there a term for what I am trying to do other than stupid, unwise, costly, etc?
Re: Dereferencing of data
by NetWallah (Canon) on Oct 09, 2003 at 18:02 UTC
    You can simplify the $arrayref creation:
    my $arrayref = [1,2,3,4,5,6,7,8]; # Note: SQUARE brackets
    Yes, you can copy arrays as you have done, and yes, it will work for AoA and AoH, but, as indicated by other posters, this is not very efficient. Why not use and pass the Array ref itself ? The only down-side is the de-referencing syntax:
    my $third_element = $arrayref->[2];
    but you get accustomed to that pretty soon.

    Once you get past the reference-passing phobia, your programs become cleaner and more efficient.
    perldoc perlref is your friend.