jimyokl has asked for the wisdom of the Perl Monks concerning the following question:
Reputation: 5
Edit
I just started learning Perl for several days.I sow some codes below, what is the type of $data, is it array or a hash? There are so many nests. Thanks.
my $data = { 'a10' => { b => 1, a => 2, }, 'bbb' => { x => 3, }, 'a2' => { z => 4, } };
Re: what is the variable type of $data = {
by Anonymous Monk on Jun 20, 2019 at 12:06 UTC
|
In this piece of code, {
starts a new, anonymous hash (that doesn't have a variable name of its
own) and returns a reference to it. The reference is stored in the
scalar variable named $data. The hash contains three keys a10, bbb, a2 and the values they have (still scalars) are also hash references.
There are two syntactically different ways to access a hash by reference: $data->{$key} (the arrow operator, ->) and ${$data}{$key} (wrap the reference in {} - where you could also put the name of the hash if it had a name). Both ways take $data, try to dereference it, access the underlying hash and return the scalar value referenced by key $key. If $data does not contain a hash reference, an exception will be raised (but if $data is undef, an anonymous hash may be created automatically and a reference to it may be stored inside $data - see autovivification).
See perlreftut and perldsc for more info.
|
[reply] [d/l] [select] |
Re^2: what is the variable type of $data = { by you!!! on Jun 20, 2019 at 12:14 UTC
|
Reputation: 1
Thank you quite a lot for your answer.
|
[reply] [edit] [/msg] |
Re: what is the variable type of $data = {
by Eily on Jun 20, 2019 at 12:18 UTC
|
++ To AnonyMonk, $data is a reference to a hash, that itself contains hashrefs (eg the value at a10 is a hashref). One way to test for that is to use ref, that will return 'HASH' in this case, or Scalar::Util's reftype, that is guarranted to always return 'HASH' even if the reference is blessed (turned into an object).
So you can check that ref $data eq 'HASH'
|
[reply] [/msg] [d/l] |
Re^2: what is the variable type of $data = { by you!!! on Jun 20, 2019 at 12:21 UTC
|
Reputation: 0
Thanks for both your quick and detailed answers.
|
[reply] [edit] [/msg] |
Re: what is the variable type of $data = {
by LanX on Jun 20, 2019 at 12:20 UTC
|
It's a hash of hashes.(HoH)
You might be confused because hashes and arrays have to incarnations in Perl
- a reference which can be stored in a $scalar
- a "list form" ° which can be stored in variables with
appropriate sigils like %hash or @array. (They are effectivity
containers for references but operating on lists)
Hashes consist of key => value
pairs of scalars ( actually
"string" => scalar
To realize nested hashes you need to put a hash reference into the value slot.
That's what's happening here.
See perldsc for more examples.
HTH :)
°) my wording
|
what is the variable type of $data = {
by you!!!
|
|