Your code works for $foo, but unfortunately not for the more complex structure

Well, as I said, easily fixed with an if. More representative sample input data gets you better answers ;-) The following should work on AoH and HoH, but not yet on AoA, and the root must be a hash. Extending this further is left as an exercise to the reader...

sub rekey { my $h = shift; KEY: for my $k (keys %$h) { if (ref $$h{$k} eq 'ARRAY') { rekey($_) for @{$$h{$k}}; my %n; for my $e (@{$$h{$k}}) { next KEY unless exists $$e{name}; die "duplicate key '$$e{name}'" if exists $n{$$e{name}}; $n{$$e{name}} = $e; } $$h{$k} = \%n; } elsif (ref $$h{$k} eq 'HASH') { rekey($$h{$k}) } } } rekey( $foo );

Update: I realized based on the sample data that you posted here that not all of your hashes in the AoHs have "name" keys. So I modified the above to skip transforming such AoHs with next KEY unless exists $$e{name};. Other approaches are of course possible too, if you can identify a useful key. Update 2: I applied that change a little too hastily, it wasn't correct as it wasn't recursing into the full data structure anymore. Fixed.


In reply to Re^3: Recursive data structure munging - arrayrefs to hashrefs (updated x2) by haukex
in thread Recursive data structure munging - arrayrefs to hashrefs by flightdm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.