my %seen = (); my $tmp ... $seen{$_}++; if ($_ ne $tmp && $seen{$tmp} == 1){ print $_; $tmp =$_; }elsif ($_ eq $tmp){ print $_ if $seen{$_} == 2; } #### 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);