my @heads; while(my ($key, $value) = each(%hash)) { # does this msg have a parent? if (my $parent = %hash{$value->{inreply}}) { # link the parent to this message push @{$parent->{nextmsg}}, $key; } else { # no parent so it must become a thread start push @heads, $key; } }