in reply to retain longest multi words units from hash

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