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

I want to copy a nested data structure. The FAQ tells me:

The Data::Dumper module on CPAN is nice for printing out data structures, and FreezeThaw for copying them. For example:

      use FreezeThaw qw(freeze thaw);
      $new = thaw freeze $old;
Where $old can be (a reference to) any kind of data structure you'd like. It will be deeply copied.

However, the following program:

use FreezeThaw qw(freeze thaw); use Data::Dumper; $hashref = { a => {}, b => {} }; print Dumper($hashref); $copy = thaw freeze $hashref; print Dumper($copy);
gives the following output:
$VAR1 = {
          'a' => {},
          'b' => {}
$VAR1 = 1;
What's the problem?

Replies are listed 'Best First'.
Re: deep copy of nested data structure
by autark (Friar) on Nov 22, 2000 at 13:54 UTC
    For cloning purposes, may I suggest using either the Storable modules dclone method
    use Storable qw(dclone); my $copy = dclone($some_ref);
    or perhaps the Clone module
    use Clone qw(clone); my $copy = clone($some_ref);
    Back to your problem at hand, the reason you get 1 as a result of the thaw method, is because it is documented to return an array. And an array in scalar context returns the number of elements, which in your case is 1. Try something like this: @copy = thaw freeze $hashref Autark.
Re: deep copy of nested data structure
by davorg (Chancellor) on Nov 22, 2000 at 14:12 UTC

    The thaw function in FreezeThaw returns an array which you are assigning to a scalar. The scalar ($copy) therefore ends up getting the number of elements in the array (in this case 1).

    Try replacing your code with this:

    ($copy) = thaw freeze $hashref;

    to force an array assignment.


    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

Re: deep copy of nested data structure
by arturo (Vicar) on Nov 22, 2000 at 20:50 UTC
    Let me also refer you to Adam's highly informative and useful node RE: Data::Dumper (Adam: Sample Usage), which helps explain how to use Data::Dumper to dump deeply nested data structures "as is."

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Re: deep copy of nested data structure
by little (Curate) on Nov 22, 2000 at 13:45 UTC
    1 is just the return value of the function ("thaw" in your case cause it's processed after "freeze") when it succeeded
    the module is changing %hashref or @hashref, you should use the strict pragma which should throw an error on your use of $hashref as it pretty much looks alike a hash
    So better print out the scalar, array or hash when you've frozen it and thawed it again to see how it works.

    Have a nice day
    All decision is left to your taste
    You might consider to use module Storable as well.
    And no, don't rely on my first sentence, I was wrong, the 1 is the length of the returned array as described below.