# 1. Only open/close the file once to append, instead of $maxid times. # 2. Use temporary values. # 3. Delete stuff you don't need immediately, not next time around loop. # 4. In this case, ($c) is same as (defined $c) (cosmetic). open(DAT,">>data/parsed-all.txt"); for(my $i = 1; $i <= $maxid; $i++) { my $currid = changeID($i); my ($c1,$c2,$c3) = ($compare1{$currid}, $compare2{$currid}, $compare3{$currid}); delete $compare1{$currid}, $compare2{$currid}, $compare3{$currid}; next if( $c1 && $c2 && $c3 && $c1 ne $c2 && $c1 ne $c3 && $c2 ne $c3 ); if( $c1 && !$c2 && !$c2 ) { print DAT $c1; next; } if( $c2 && !$c1 && !$c3 ) { print DAT $c2; next; } if( $c3 && !$c1 && !$c2 ) { print DAT $c2; # <-- BUG HERE! next; } if( $c1 && $c2 ) { if( $c1 eq $c2 ) { print DAT $c1; next; } } if( $c1 && $c3 ) { if( $c1 eq $c3 ) { print DAT $c1; next; } } if( $c2 && $c3 ) { if( $c2 eq $c3 ) { print DAT $c2; next; } } } close(DAT);