[ACCEPTED]-Perl Regular Expressions + delete line if it starts with #-perl

Accepted answer
Score: 13

You don't delete lines with s///. (In a loop, you 2 probably want next;)

In the snippet you posted, it 1 would be:

while (my $line = <IN>) {
    if ($line =~ /^\s*#/) { next; }
    # will skip the rest of the code if a line matches

    ...
}

Shorter forms /^\s*#/ and next; and next if /^\s*#/; are possible.


perldoc perlre

/^\s*#/
  • ^ - "the beginning of the line"
  • \s - "a whitespace character"
  • * - "0 or more times"
  • # - just a #
Score: 7

Based off Aristotle Pagaltzis's answer you could do:

perl -ni.bak -e'print unless m/^\s*#/' deletelines.txt

Here, the -n switch 12 makes perl put a loop around the code you 11 provide which will read all the files 10 you pass on the command line in sequence. The 9 -i switch (for “in-place”) says to collect 8 the output from your script and overwrite 7 the original contents of each file with it. The 6 .bak parameter to the -i option tells perl 5 to keep a backup of the original file 4 in a file named after the original file 3 name with .bak appended. For all of these 2 bits, see perldoc perlrun.

deletelines.txt 1 (initially):

#a
b
     #a 
#   a
  c
         # a

becomes:

b
  c
Score: 2

Program (Cut & paste whole thing including 1 DATA section, adjust shebang line, run)

#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
  next if /^\s*#/;  # skip comments
  print;            # process data
}

__DATA__
# comment
data
  # another comment
more data

Output

data
more data
Score: 0
$text ~= /^\s*#.*\n//g

That will delete all of the lines with # in 3 the entire file of $text, without requiring 2 that you loop through each line of the text 1 manually.

More Related questions