Perl Find Blank Lines

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe for identifying blank lines in a file. Blank lines can contain spaces or tabs, or they can contain a combination of spaces and tabs. Variations on these expressions can be useful for stripping blank lines from a file.

[edit] code

#!/usr/bin/perl -w
use strict;
 
open( FILE, $ARGV[0] ) || die "Cannot open file!";
 
my $i = 0;
 
while ( <FILE> )
{
    $i++;
    next unless /^\s*$/;
    print "Found blank line at line $i\n";
}
 
close( FILE );

[edit] How It Works

The previous \s sequence represents a character class. A character class can match an entire category of characters, which \s does here even though it's a category that contains only tabs and spaces. Other character classes match far more examples, such as \d, which matches digits in most regular expression flavors. Character classes are shorthand ways of describing sets of characters.

Regular Expression Description
^ starts the beginning of the line, followed by . . .
\s any whitespace character (a tab or space) . . .
* zero or more times, followed by . . .
$ the end of the line.
Personal tools