#!/usr/bin/perl use strict; use warnings; my %hash = map {$_ => undef} 'a' .. 'z'; my ($at_once, $cnt, @bot_n, %known) = (3, 0, (), ()); while (1) { while (my ($key, $val) = each %hash) { next if defined $val; if (exists $known{$key}) { $hash{$key} = $known{$key}; next; } my $inserted; for (0 .. $#bot_n) { if ($key lt $bot_n[$_]) { splice @bot_n, $_, 0, $key; $inserted = 1; last; } } push @bot_n, $key if ! $inserted; pop @bot_n if @bot_n > $at_once; } last if ! @bot_n; %known = (); for (@bot_n) { $known{$_} = ++$cnt; } @bot_n = (); } use Data::Dumper; print Dumper(\%hash);