That cannot be the output from Data::Dumper, because it lacks commas between some of the elements. When you post imprecise samples and claim that they're the output of something that generates precise, and syntactically correct data structures, we're unable to trust your problem description, much less know how to fill in the missing parts.

Your expected result is also impossible, unless we should be interpreting it as simple text. From a Perl data structure point of view, 'abc,def' => { 'item1,item2,,item4 }, is nonsensical; the curly braces mean "anonymous hash", and the leading single quote isn't balanced by any closing single quote. Given the ambiguity introduced by leaving quotes unbalanced, we also can't determine which of the commas should be interpreted as literal text, or as operators.

Also, since hash elements have no predictable or useful order, it would be helpful to specify how the "item1" and so on elements should be ordered (assuming you really intend for them to be array elements).

With those flaws in the question making it impossible to precisely know what is being asked, it is also impossible to give an answer that is guaranteed to precisely match your needs. But this is an attempt at getting close:

use Data::Dumper; my %orig = ( 'abc,def' => { ',,,item4' => 1, 'item1,,,' => 1, ',item2,,' => 1, }, 'kln,mno' => { ',,,item4' => 1, 'item1,,,' => 1, }, ); my %new; foreach my $top ( keys %orig ) { push @{$new{$top}}, $_ for keys %{$orig{$top}}; } print Dumper \%new;

The output that produces is this:

$VAR1 = { 'abc,def' => [ 'item1,,,', ',item2,,', ',,,item4' ], 'kln,mno' => [ 'item1,,,', ',,,item4' ] };

Dave


In reply to Re^3: merge with multiple row with same key by davido
in thread merge with multiple row with same key by tcheungcm

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.