my %seen = (); my $tmp; my $id; ... if ($_ ne $tmp){ $seen{$tmp}=$id++; } and then in the second loop: print $_ foreach (sort{$seen{$a}<=>$seen{$b}}keys %seen);