In Perl, why do I need to @b = @{dclone(\@a)}? Why can't I just @b = dclone(\@a)?
arrays, perl
Solution
`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.
Problem
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?