Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: strip perl comment lines

by repson (Chaplain)
on Feb 07, 2001 at 17:06 UTC ( #56945=note: print w/replies, xml ) Need Help??

in reply to strip perl comment lines

I didn't like like a number of points of style in your code, so I fiddled with it. There are more changes than I feel like listing, but you can tell what they are yourself. So I'll just show my changed (not necessarily improved) version and you can decide if it's an (?:dis)?improvement.
#!perl -w use strict; unless (@ARGV==2) { die <<EOF; $0 strips comment lines beginning with # from perl code usage: $0 infile outfile set outfile to \"display\" to just show result EOF } my $infile = shift; my $outfile = shift; my $full_code = ''; my $bad_lines = 0; my $good_lines = 0; open(IN,"< $infile") or die "Can't open $infile: $!\n"; while (<IN>) { if ( /^\s*#[^!]/ ) { # if comment line $bad_lines++; } else { $good_lines++; $full_code .= $_; # add to code } } close(IN) or die "Can't close $infile: $!\n"; if ($outfile eq 'display') { print $full_code; } else { open(OUT,"> $outfile") or die "Can't write to $outfile: $!\n"; print OUT $full_code; close(OUT) or die "Can't close $outfile: $!"; } print ($good_lines+$bad_lines) . "lines read from $infile\n", "$bad_lines comment lines detected in $infile\n", "$good_lines lines written to $outfile\n";

Replies are listed 'Best First'.
Re: Re: strip perl comment lines
by epoptai (Curate) on Feb 07, 2001 at 17:48 UTC
    Thanks for the lesson repson. I see the wisdom of your changes:

    • replaced multiple print statements with here docs
    • eliminated useless scalar use
    • replaced the hash with string concatenation via assignment op
    • one while instead of for loops, sorting and subroutine
    • more elegant flow eliminates need for multiple exits

    But the final print statement:

    print ($good_lines+$bad_lines) . "lines read from $infile\n", "$bad_lines comment lines detected in $infile\n", "$good_lines lines written to $outfile\n";
    Failed on 5.00503 with the warning:
    print (...) interpreted as function at line 40.
    So /me sweeps up around the monastery:
    my$lines=($good_lines+$bad_lines); print "$lines lines read from $infile\n", "$bad_lines comment lines detected in $infile\n", "$good_lines lines written to $outfile\n";
    ps - fixed omission of the 2nd $0 in the original.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://56945]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2018-02-20 06:09 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (267 votes). Check out past polls.