If you're using Perl 5.005_03 or higher, this is how I'd write your code:
open my $results, '<', $outputfile
or die "Cannot open '$outputfile' for reading: $!\n';
open my $cleaned, '>', $new_outputfile
or die "Cannot open '$new_outputfile' for writing: $!\n";
{
my %seen;
local $_;
while ( <$results> ) {
chomp;
next if $seen{ $_ }++;
print $cleaned $_, "\n";
}
}
# Always close in the reverse order of opening.
close $cleaned;
close $results;
unlink $results
or die "Cannot unlink '$outputfile': $!\n";
File::Copy::move( $new_outputfile, $outputfile )
or die "Cannot rename '$new_outputfile' to '$outputfile': $!\n";
The changes:
- Use 3-arg open for safety.
- Use lexicals for filehandles instead of globals. (That's the difference between 'my $fh' and 'FH'.)
- Always check the return values of system commands.
- If you fail a system command, then stop processing immediately. It's dangerous to continue unless you have a way of cleaning up what went wrong.
- Don't read the file into memory. It might be small now, but it will probably grow.
- If you intend on using $_, localize it so that you don't trample on anyone.
- You're not paying for your whitespace, so use whitespace liberally. It will increase readability in the long run.
- If you open it, then close it as soon as you're done with it.
- If you open two things, close them in reverse order.
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.