开发者

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

开发者 https://www.devze.com 2022-12-19 18:56 出处:网络
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 t

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 tri开发者_如何转开发ed, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消