简体   繁体   中英

How do I copy an array using a reference in Perl?

If I do the following, it works fine:

print $ref->{element}->[0]->{data};

I would like to see how many references are in the array so that I can loop through them, but I am having a hard time doing that.

Here is the code I have tried, but it doesn't work:

my @array = @$ref->{element};

foreach(@array) {
    print $_->{data};
}

I get an "Not an ARRAY reference" error

Hashes of lists are tricky that way. @$ref->{element} gets parsed as (@$ref)->{element} , dereferencing $ref instead of $ref->{element} .

Try

my @array = @{$ref->{element}}

or

my $size = scalar @{$ref->{element}}

Gory details in perllol .

As a general aid in debugging, give Data::Dumper a look. It's invaluable for poking about in the innards of data structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM