Here's a solution that takes your posted input and creates your expected output.

#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my %data = ( 'rendition' => '3', 'automation' => '2', 'saturation' => '3', 'mass creation' => 2, 'automation technology' => 2, 'automation technology process' => 3, ); dd \%data; for my $multi_key (grep y/ / / != 0, keys %data) { next unless exists $data{$multi_key}; for my $any_key (keys %data) { next if $any_key eq $multi_key; delete $data{$any_key} if 0 == index $multi_key, $any_key; } } dd \%data;

Output:

{ "automation" => 2, "automation technology" => 2, "automation technology process" => 3, "mass creation" => 2, "rendition" => 3, "saturation" => 3, } { "automation technology process" => 3, "mass creation" => 2, "rendition" => 3, "saturation" => 3, }

I saw your post (in isolation) before I logged in, thought it looked like an interesting problem, and wrote my solution before looking at any other replies. My code doesn't use any regexes or sorting which may help efficiency (see the final dot-point below for a clarification of that statement); any similarities to components used in other solutions is purely coincidental (although perhaps not surprising, e.g. you'll see delete used quite a bit).

I had a few issues with your spec; and now see I'm not alone. Again, some of these points may already have been raised.

Update (typo): s/beyong/beyond/

— Ken


In reply to Re: retain longest multi words units from hash by kcott
in thread retain longest multi words units from hash by Anonymous Monk

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.