foreach $line (@lines) { my $id = $line =~ m/ID No: (\d+)/; if ($seen{$id}++){ # ... #### foreach $line (@lines) { my ($id) = $line =~ m/ID No: (\d+)/; if ( ! $seen{$id}++){ # ... #### open my $in_fh, '<:utf8', 'input.txt' or die "Can't read 'input.txt': $!"; my @lines = <$in_fh>; #### open my $in_fh, '<:utf8', 'input.txt' or die "Can't read 'input.txt': $!"; open my $purge_fh, '>>:utf8', 'purge.txt' or die "Can't append to 'purge.txt': $!"; open my $uniq_fh, '>:utf8', 'data.txt' or die "Can't write 'data.txt': $!"; my %seen; while ( my $line = <$in_fh> ) { my ($id) = ($line =~ /ID No: (\d+)/); if ( ! $seen{ $id }++ ) { print $uniq_fh, $line; $new_uniq++; } else { print $purge_fh, $line; } } close $in_fh or die "Close failed for input: $!"; close $purge_fh or die "Close failed for purge.txt: $!"; close $uniq_fh or die "Close failed for data.txt: $!";