Beefy Boxes and Bandwidth Generously Provided by pair Networks kudra
go ahead... be a heretic
 
PerlMonks  

Re: Manipulate deepest values in complex hash structures

by Laurent_R (Priest)
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

Hi,

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 walk_HoA.pl 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.


Comment on Re: Manipulate deepest values in complex hash structures
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1031290]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-04-20 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls