Friday, October 19, 2007

Skipping Blank Lines in Input Files Using Perl

Hey There,

This is all based on the presumptions that you've read in a file, examined the comma-delimited fields of the lines and put them back together (you've performed whatever actions you needed to on the existing lines and now want to move or print the output, but don't want to print any lines that don't have any content after your parsing).

After you've executed the line of code that puts your line back together (added the values back into a comma delimited line), you can do a chomp on the scalar value (the $ string).

So, rather than just add an eol character (\n,\r, etc), make it conditional to remove thost blank lines (below example might not be exactly what you're working with, but the spirit's the same).

I've used SPACE to denote an actual space key type and TAB to denote an actual tab key type. You can use \s and \t for this also, but it's my habit. Had to use the SPACE and TAB words here because the space and tab key strikes won't show in this post)

Run this in a loop on your input (while )

chomp($line);
if ( $line !~ /^SPACE*TAB*$/ ) {
print "$line\n";
}

And you've got your output, parsed per your requirements and no empty lines mucking it up :)

, Mike