my @array = @{$array_ref};
I'm not entirely sure what thi开发者_运维知识库s array is storing. Can anyone care to explain to me what is happening? Thanks.
$array_ref
presumably holds a reference to an array, which is different from an array itself. An array (named @some_array
) has elements (unless it's empty). An array ref (named $some_arrayref
) is a scalar value that is used to reference an actual array. The actual array may be a named array (as in, it has a variable name), or may be an anonymous array (as in, no named variable, but referred to exclusively by reference).
To use the elements held in the array referred to by $array_ref
, you have to dereference it. One syntax is @$array_ref
(read that as "The array (@
) referred to by the scalar ($
) named array_ref
). I've never been a fan of jamming a bunch of sigils together (the @
, $
and %
symbols) when dereferencing. I feel it hampers readability of the code, particularly as the references become more complex or nested. Perl allows for curly brackets, which help to disambiguate and visually clarify what's going on. @{$array_ref}
can be read as dereference as an array ( @{....}
) the array referred to by $array_ref
.
From Perl's POD, have a look at perlreftut. It's a great starting point.
The code makes a top-level copy of the array referenced by $array_ref and stores it in @array.
To make a deep-level copy, use dclone from Storable:
use Storable;
@array = @{ dclone( $array_ref ) };
See perldoc Storable
for details.
Storable is a standard module that is install with Perl. To see a list of all standard pargmatics and modules, see perldoc perlmodlib
.
This is simply dereferencing the array ref. $array_ref
contains a reference to an array, @array
is set to the contents of the referenced array.
$ perl -E 'my $a = [1, 2, 3]; my @b = @{$a}; say $a; say @b'
ARRAY(0x100803ea0) # a reference to an array
123 # actual array
You need to read perlref.
In short, @array
is the same array that $array_ref
was pointing to. That is the most precise answer that I can give without knowing what got put into $array_ref
.
$array_ref
is a reference to a list / array.
so in order to dereference it in a list content and get all the contents, you use
@{$array_ref}
and this can be assigned into a different array / list like:
my @array = @{$array_ref};
精彩评论