#!/usr/bin/perl use warnings; use strict; #example data below. my %data = ( #Partno List of orders "A1111" => [qw/12345 1234 123456 2345 233 23456/], "B2222" => [qw/12345/], "C3333" => [qw/12345 6789/], "D4444" => [qw/12345 1234 6789/], "E5555" => [qw/12345 1234 6789 99999 999999 444444 22222 111/], "F6666" => [qw/888888 9999999 6789/], ); #Find the 5 numerically largest orders for each partno, and display them. foreach my $part_no (sort keys %data) { my @matching_orders; #Sort each order by number, largest first.. @matching_orders = sort { $a <=> $b } @{$data{$part_no}}; #We want upto the most recent five. Nasty hack. my $idx = $#matching_orders-4; $idx = 0 if($idx < 0); my @top_five = reverse splice @matching_orders, $idx; $data{$part_no} = \@top_five; } #I now know the first element of each part_no array is #the largest order number that part_no appears on. #sort by that element. foreach my $part_no (sort { ${$data{$a}}[0] <=> ${$data{$b}}[0] } keys %data) { #Now display them print "Part Number \"$part_no\" was found on: "; print join ", ", @{$data{$part_no}}; print "\n"; }