You're using the 3-argument form of open which is good but you're not checking whether it worked which is less good. Try doing something like the following whenever you open a file:
open my $file_handle, $mode, $filename or die $!;
While it's a matter of personal style, I'd use lowercase characters for the file handle variables; leaving uppercase for global file handles such as STDOUT, DATA, etc. and constants.
Regarding the two file-related errors you questioned:
-
You opened $TMPOUT for writing only but then tried to read from it with cp().
-
You closed $SCRATCH then tried to use it in cp().
There's two issues with your regular expressions:
-
You don't separate the characters in a character class with pipe characters: [-&_+'] is all you need but do look at the Version 8 Regular Expressions section in perlre regarding the positioning of a hyphen character.
-
By converting those special characters to spaces, you won't differentiate between Group One and GroupOne - you'll need to do something else here.
Here's a piece of code that demonstrates what you want:
#!perl
use strict;
use warnings;
my %seen;
while (my $line = <DATA>) {
my ($key, $rest) = split /,/, $line, 2;
$key =~ s{ [-&_+'] }{ }msx;
$key =~ s{ ( [a-z] ) ( [A-Z] ) }{$1 $2}msx;
if ($seen{$key}++) {
print STDERR join '', 'DUP: ', $line;
}
else {
print STDOUT join '', 'NEW: ', $key, ',', $rest;
}
}
__DATA__
Group One,Captain,Phone Number,League Pos,etc.
Group-One,Captain,Phone Number,League Pos,etc.
GroupOne,Captain,Phone Number,League Pos,etc.
Group Two,Captain,Phone Number,League Pos,etc.
Group Three,Captain,Phone Number,League Pos,etc.
Here's the output:
$ del_dup_prob.pl
NEW: Group One,Captain,Phone Number,League Pos,etc.
DUP: Group-One,Captain,Phone Number,League Pos,etc.
DUP: GroupOne,Captain,Phone Number,League Pos,etc.
NEW: Group Two,Captain,Phone Number,League Pos,etc.
NEW: Group Three,Captain,Phone Number,League Pos,etc.
Commenting out the second regex (which converts GroupOne to Group One in $key) the output becomes:
$ del_dup_prob.pl
NEW: Group One,Captain,Phone Number,League Pos,etc.
DUP: Group-One,Captain,Phone Number,League Pos,etc.
NEW: GroupOne,Captain,Phone Number,League Pos,etc.
NEW: Group Two,Captain,Phone Number,League Pos,etc.
NEW: Group Three,Captain,Phone Number,League Pos,etc.
Obviously, you'll need to read in your input file and you won't want the NEW: and DUP: strings I added for illustrative purposes but otherwise you could run this code as:
script_name input_filename > unique_rows_filename 2> duplicate_rows_fi
+lename
Finally, given the list of special characters in your regex, there's more variety to your input data than you've shown here. That's fine, but you may need to tweak the regexes I've provided.