in reply to Best Hash Practices?
I'm not certain that it is a best practice, but I find that Data::Diver and eval() help out a lot when dealing with hashes and arrays.
#!/usr/bin/env perl use Data::Dumper qw| Dumper |; use Data::Diver qw| Dive DiveVal DiveRef DiveDie DiveError DiveClear | +; my $h = { key => 'value', hoh => { key => 'value' }, hoa => [ 'a', 'b', 'c' ], deep => { values => { are => 'supported' } }, }; Dive($h, 'key') && warn "'key' is there"; !Dive($h, 'nokey') && warn "'nokey' is not there"; warn "notice 'nokey' was not created"; warn Dumper $h; warn "Values are: " . join(', ', eval {@{Dive($h, 'hoa')}}); warn "No errors for non arrays: " . join(', ', eval {@{Dive($h, 'empty +')}}); warn "Deep values: ". Dive($h, qw| deep values are |); !Dive($h, qw| deep values that is not there |) && warn "Missing Deep v +alues are safe"; __END__ 'key' is there at ./test.pl line 12. 'nokey' is not there at ./test.pl line 13. notice 'nokey' was not created at ./test.pl line 14. $VAR1 = { 'deep' => { 'values' => { 'are' => 'supported' } }, 'hoa' => [ 'a', 'b', 'c' ], 'hoh' => { 'key' => 'value' }, 'key' => 'value' }; Values are: a, b, c at ./test.pl line 17. No errors for non arrays: at ./test.pl line 18. Deep values: supported at ./test.pl line 19. Missing Deep values are safe at ./test.pl line 20.
Some of those are still not beautiful ( especially array dereference ), but I find it a clean way to deal with hashes, as it already implements the autovivification and error handling logic.
|
|---|