merlyn beat me with some of his comments (I'm only on my second cup of coffee) but I would add that if you think it unlikely that here-docs (or multiline quoted strings) will contain comments, I know I have such programs. Additionally, it is also conceivable that a # character could be used as a delimiter for one of the quoting or regex operators:

$string =~ m# (some pattern) #x;

If I were to do this I would take merlyn's suggestion of using '-' (but also allow the second argument to be optional), open the output handle up front (using $! in the error message) and take care of output right in the while loop so we don't need to build up the output in memory -- something along the lines of:

#!/usr/bin/perl -w use strict; die <<USAGE unless @ARGV and @ARGV <= 2; $0 strips comment lines beginning with # from perl code usage: perl $0 infile [outfile] (output to stdout if no outfile given) USAGE my $infile = shift; my $outfile = shift || '-'; open(IN,"< $infile") or die "Couldn't open $infile: $!"; open(OUT, ">$outfile") or die "Couldn't open $outfile: $!"; my ($code, $comments) = (0,0); while(<IN>) { $comments++ and next if /^\s*#[^!]/; print OUT; $code++ } close IN; close OUT; my $total = $code + $comments; print<<SUMMARY; $total lines read from $infile $comments comment lines detected in $infile $code lines written to $outfile SUMMARY

But, in reality, I wouldn't really do this because it is destined to fail on some Perl code for reasons already given, and we haven't even mentioned accidentally stripping things that look like comments in POD sections.


In reply to Re: strip perl comment lines by danger
in thread strip perl comment lines by epoptai

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.