Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Manipulate deepest values in complex hash structures

by Laurent_R (Canon)
on Apr 29, 2013 at 22:26 UTC ( #1031290=note: print w/replies, xml ) Need Help??

in reply to Manipulate deepest values in complex hash structures


even though the code below compiles cleanly and does the expected work for the example chosen, please consider it as a pseudocode example (rather than a real solution) of a recursive approach to the traversing of your data structure. I haven't tested any more complicated examples, I have considered that the structure could only include hash and array ref's and made a number of other simplifications.

I agree with Rolf that it is better to use a coderef, so that's what I did (simply printing the values in my code below) rather than a hardcoded regexp, so as to make the walk_data_struct function usable for many other purposes.

my %hash = (jan => [january, '01'], feb => [february, '02'], mar => [m +arch, '03']); walk_data_struct (\%hash, sub { my $leaf = shift; print "$leaf \n";}); sub walk_data_struct { my ($data_ref, $code_ref) = @_; if (ref $data_ref) { if (ref ($data_ref) eq "HASH") { walk_data_struct ($data_ref->{$_}, $code_ref) foreach keys + %$data_ref; } else { walk_data_struct ($_, $code_ref) foreach @$data_ref ; } } else { &{$code_ref} ($data_ref); } }
This prints the leaves of my simple HoA:
$ perl february 02 january 01 march 03
EDIT: Ooops, I had not seen that some actual solutions had been proposed meanwhile. The last post I had seen when I wrote the above was Rolf's post giving guidelines on how to solve the problem, but without any code. I had not seen any of the later posts with actual code. For some reason, I had missed the later posts. I still leave my solution, hoping that it might still help a little bit.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1031290]
[holli]: i don't know. meat and tomatoes don't belong anywhere near each other in my book
[holli]: unless the meat is in sausage form and the tomatoes being ketchup, that is
[Discipulus]: no ragł? i'm sorry..;=)

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2017-11-22 09:27 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (316 votes). Check out past polls.