Speaking of style... I took the liberty of rewriting your script.
#!/usr/bin/perl -w
use strict;
my $infile = shift;
my $outfile = "$newfile.tmp";
open my $infh, '<', $infile or die "Cannot open $infile: $!\n";
open my $outfh, '>>', $outfile or die "Cannot open $outfile: $!\n";
while (<$infh>) {
s/^\s+//g;
s/\s+$//g;
print $outfh $_, "\n" or die "Cannot write to $outfile: $!\n";
}
close my $outfh or die "Cannot close $outfile: $!\n";
close my $infh or die "Cannot close $infile: $!\n";
system('perltidy', $outfile) == 0 or die "Perltidy failed\n";
rename "$outfile.tdy", $infile or die "Cannot rename $outfile.tdy: $!\
+n";
unlink $outfile or die "Cannot unlink $outfile: $!\n";
chmod 0755, $infile or die "Cannot chmod $infile: $!\n";
Changes include:
- use strict
- Got rid of all global variables, including file handles
- Modern three argument open to avoid bugs
- Sane indenting instead of an awful mess
- Parens only where needed instead of ... I guess at random
- Error checking on all system stuff. In the real world, many things can go wrong
- Passing a list of $_ and \n to print instead of a concatenated string, for efficiency
- Renaming of 'newfile'. Why 'new' anyway?
I don't understand:
- why you remove whitespace. perltidy does that for you.
- why you chmod the file using a hardcoded value (use the original permissions!)
- why there is no error message that indicates usage if @ARGV != 1
And you should probably not just filter whitespace like that. The whitespace might be in a string literal!
Juerd
- http://juerd.nl/
- spamcollector_perlmonks@juerd.nl (do not use).
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.