If you tell enough stories, perhaps the moral will show up.

2007-10-25

Read a Text File with Comments

This is a little Perl idiom to open a text file and read all the non-comment lines.

Key parts are

  • <LINELIST> yields all the lines in the filehandle into the default scalar $_
  • s/^\s*//; s/\#.*$//; s/\s*$//; removes (==substitutes nothing in place of) first any space at the front of the line second any trailing comment and third any trailing space in $_
  • chomp strips the newline from $_
  • next if /^$/ skips past the rest of the loop processing if $_ is empty (it matches beginning of line immediately followed by end of line)
All of this could be directed to a named scalar variable, but using the default pays off in compact code that can be cut and pasted elsewhere.
my $listfn="linelist.txt";
open LINELIST, "<$listfn" or die "Open $listfn $!";
while (<LINELIST>) {
    s/^\s*//; s/\#.*$//; s/\s*$//; chomp; next if /^\s*$/;
    print "$_\n"; # Or whatever else you want to do.....
}
Obviously printing is a bit dull -- instead you could drop the lines into an array:
push @linelist, $_;
Use grep to search it:
@results = grep((/$mypatt/i), @linelist);
The i after the pattern makes for case insensitivity, and you have to
use locale;
to get it right for all character sets.

No comments: