in reply to Re: Return a Deep Hash Reference from Array of Keys
in thread Return a Deep Hash Reference from Array of Keys
Interesting idea, but it doesn't actually work.
Here is the output:
#! /bin/perl use Data::Dumper; my $hash = { 'wheels' => { 'four' => { 'car' => { 'plain' => { 'sporty' => 'honda', 'retro' => 'volkswagon', }, 'fancy' => { 'red' => 'ferrari', 'silver' => 'maserati', }, }, 'truck' => { 'light' => { 'chevy' => 'pickup', }, 'utility' => { 'us' => 'mail', 'city' => 'trash', 'muni' => 'power', 'corp' => { 'dom' => 'dominion p +ower', 'vap' => 'virginia p +ower', }, }, }, }, 'one' => 'Unicycle', 'two' => { 'pedals' => 'bicycle', 'motorized' => 'motorcycle', }, 'three' => 'tricycle', }; ##--------------------------- ## DEEP REFERENCE ##--------------------------- fetch2($hash, 'wheels'); fetch2($hash, 'wheels', 'four', 'truck', 'utility', 'blah'); fetch2($hash, 'wheels', 'four', 'truck', 'utility', 'corp', 'dom'); ## Using your suggested technique sub fetch2 { my ($hash, @keys) = @_; print "==> Fetching [" . join(', ', @keys) . ']' . "\n"; print Dumper $hash->{shift @keys}{shift @keys}; }
Produces:
==> Fetching [wheels] $VAR1 = undef; ==> Fetching [wheels, four, truck, utility, blah] $VAR1 = { 'car' => { 'plain' => { 'sporty' => 'honda', 'retro' => 'volkswagon' }, 'fancy' => { 'silver' => 'maserati', 'red' => 'ferrari' } }, 'truck' => { 'light' => { 'chevy' => 'pickup' }, 'utility' => { 'city' => 'trash', 'muni' => 'power', 'us' => 'mail', 'corp' => { 'dom' => 'dominion p +ower', 'vap' => 'virginia p +ower' } } } }; ==> Fetching [wheels, four, truck, utility, corp, dom] $VAR1 = { 'car' => { 'plain' => { 'sporty' => 'honda', 'retro' => 'volkswagon' }, 'fancy' => { 'silver' => 'maserati', 'red' => 'ferrari' } }, 'truck' => { 'light' => { 'chevy' => 'pickup' }, 'utility' => { 'city' => 'trash', 'muni' => 'power', 'us' => 'mail', 'corp' => { 'dom' => 'dominion p +ower', 'vap' => 'virginia p +ower' } } } };
Whereas the expected result should be:
==> Fetching [wheels] $VAR1 = { 'three' => 'tricycle', 'one' => 'Unicycle', 'two' => { 'pedals' => 'bicycle', 'motorized' => 'motorcycle' }, 'four' => { 'car' => { 'plain' => { 'sporty' => 'honda', 'retro' => 'volkswagon' }, 'fancy' => { 'silver' => 'maserati', 'red' => 'ferrari' } }, 'truck' => { 'light' => { 'chevy' => 'pickup' }, 'utility' => { 'city' => 'trash', 'muni' => 'power', 'us' => 'mail', 'corp' => { 'dom' => + 'dominion power', 'vap' => + 'virginia power' } } } } }; ==> Fetching [wheels, four, truck, utility, blah] (nothing, because it doesn't exist) ==> Fetching [wheels, four, truck, utility, corp, dom] $VAR1 = 'dominion power';
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Return a Deep Hash Reference from Array of Keys
by Laurent_R (Canon) on Aug 16, 2013 at 21:13 UTC | |
by bratwiz (Sexton) on Sep 13, 2013 at 18:20 UTC | |
by Laurent_R (Canon) on Sep 13, 2013 at 18:43 UTC |