3 ms·
%nested = (foo => { bar => { baz => "quux" } }); Access the leaf with $nested->{foo}{bar}{baz} If the keys are in variables, it becomes $nested->{$x
by gbacon 6y ago
%nested = (foo => { bar => { baz => "quux" } });
Access the leaf with
$nested->{foo}{bar}{baz}
If the keys are in variables, it becomes
$nested->{$x}{$y}{$z}
For dynamic depth, do you have a specific use case in mind? If I have a tree, I’m probably going to search it rather than using a hardcoded path.
- kbenson 6y agoThis is why we use strict! The extra arrow is unneeded, as you're working on the actual hash, not a reference to the hash. This is a compiler error with use strict though, so it's not something you would generally be bitten with when writing real code, just internet comments. :)
- gbacon 6y agoWhoops, good catch! I had references on the brain. For completeness, that makes it either $nested{$x}{$y}{$z} or after initializing with curly brackets rather than parentheses to construct a new reference to an anonymous hash $nested = { … }; and then use the arrow to dereference as in the grandparent.
- cookiecaper 6y agoI think the point is not that Perl's rules don't make sense -- it's that they're much less obvious than those in many competing languages. In Python, lists are `l = [1, 2, 3]` and dicts are `d = {"key": val}`. Both structures can be nested without any change to the semantics.