my %nxt; my %prev; my $prv; for (sort { $a <=> $b } keys %hash) { if (defined $prv) { $nxt{$prv} = $_; $prev{$_} = $prv; } $prv = $_; }