in reply to Style, *again*

I'm just a lowly beginner compared to you guys, here is what I use for "style". :-) Just write whatever you want, or cut'n'paste code, then run it thru the following script. Presto! Automatic style.
#!/usr/bin/perl #usage: $0 script use warnings; $newfile = $ARGV[0]; $outfile = $newfile . '.tmp'; open( FH, $newfile ) or die $!; open( OUT, ">> $outfile" ); while (<FH>) { # $_ =~ s/^\s+//g; #only gets leading whitespace $_ =~ s/^\s+|\s+$//g; #gets trailing also #next if $_ =~ /^\s*$/; #removes blank lines # $_ =~ s/[\t]+//g; #gets tabs and ws inside strings + #and leaves \n print OUT $_ . "\n"; } close FH; close OUT; system( "perltidy", $outfile ); rename( "$outfile.tdy", $newfile ); unlink $outfile; chmod 0755, $newfile; exit;

Replies are listed 'Best First'.
Re: Re: Style, *again*
by Juerd (Abbot) on Apr 09, 2003 at 18:53 UTC

    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).
    

      Thanks for "purifying" that script Juerd. :-)