in reply to Regex in a printfile?

That's pretty inefficient as it will read in all of the matching lines from your input before it prints things out.

That aside, if you want to remove comments from all lines before printing and remove empty lines completely you probably want something more like this.

while( <INFILE> ) { chomp; s/^\s*#.*$//; next unless length $_; print OUTFILE $_, "\n"; }

Update: As is remarked below, the s/// needs to be anchored. And yes, this skips empty lines. Now where's my caffeine . . .

Replies are listed 'Best First'.
Re^2: Regex in a printfile?
by ikegami (Patriarch) on Nov 15, 2006 at 20:29 UTC

    That removes all empty lines, not just those that were comments. Fix:

    while (<INFILE>) { chomp; next if /^\s*#/; s/\s*#.*$//; print OUTFILE "$_\n"; }
      The problem with s/\s*#.*$//; is that you might start breaking scripts unexpectedly. Given this (contrived but not unlikely) code snippet

      my @fred = (1, 2, 3, 4, 5); my $lastSub = $#fred; print qq{$lastSub\n};

      running your substitution will result in

      my @fred = (1, 2, 3, 4, 5); my $lastSub = $ print qq{$lastSub\n};

      Perhaps something like

      s{(?<!\$)#.*$}{};

      would be better but there may be other syntax where the hash is not the start of a comment that I haven't thought of.

      Cheers,

      JohnGG

      Update: Found another non-comment occurrence of the # character in the colour values in Tk programs, e.g.

      -background => #101010,

      so perhaps now

      s{(?<!\$)#(?![0-9a-fA-F]{6}).*$}{};