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.
This prints the leaves of my simple HoA: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); } }
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.$ perl walk_HoA.pl february 02 january 01 march 03
|
---|
In Section
Seekers of Perl Wisdom