Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, why do I need to @b = @{dclone(\@a)}? Why can't I just @b = dclone(\@a)?

Tags:

arrays

perl

I have an array of various things including scalars and arrays. I want to make a copy of it, and tried the following:

@b = dclone(\@a)

but then when I try to read one of the scalar values from b, I get nothing back.

Everything appears to work when I copy it this way, though:

@b = @{dclone(\@a)}

What is the reason?

like image 517
shino Avatar asked Jan 06 '10 16:01

shino


1 Answers

dclone takes and returns references.

#! /usr/bin/perl

use Storable qw/ dclone /;

my @array = ( [1 .. 3], qw/ apple orange banana / );
my $copy = dclone \@array;

print ref($copy), "\n";

The output of the program above is ARRAY, so to get a deep-cloned array, use

my @copy = @{ dclone \@array };

To show what was going on without the dereference, the output of

my @copy = dclone \@array;

for (0 .. 4) {
  print "$_: ",
        (defined $copy[$_] ? $copy[$_] : "<undef>"),
        "\n";
}

is

0: ARRAY(0x1d396c8)
1: <undef>
2: <undef>
3: <undef>
4: <undef>

So assigning the result of dclone to an array will produce a single-element array, and trying to fetch any value other than the zero-th yields the undefined value.

like image 95
Greg Bacon Avatar answered Oct 20 '22 17:10

Greg Bacon