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

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";


Comment on Re: strip perl comment lines
Download Code
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 unc_rep.pl 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://56945]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2014-12-20 08:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls