Remove Blank Lines in Perl: Best Methods

There are various ways to remove blank lines in Perl. One commonly used method is:

  1. Delete blank lines using regular expressions.
while (<>) {
    next if /^\s*$/;  # 如果行只包含空格或制表符,则跳过
    print;
}

Read each line of the input file using the <> operator. Skip lines that contain only spaces or tabs with next if /^\s*$/. Print out the remaining lines.

  1. Remove blank lines using the chomp function.
while (<>) {
    chomp;  # 删除行末尾的换行符
    next if /^\s*$/;  # 如果行只包含空格或制表符,则跳过
    print $_ . "\n";
}

The chomp function is used to remove the newline character at the end of a line. The rest of it is the same as the first method.

  1. Delete blank lines using arrays and the grep function.
while (<>) {
    push @lines, $_;  # 将每一行存储在数组中
}

@lines = grep { /\S/ } @lines;  # 使用grep函数删除只包含空格或制表符的行

foreach my $line (@lines) {
    print $line;
}

Store each line in the array @lines. Use the grep function and the regular expression /\S/ to filter out lines that contain only spaces or tabs. Finally, use a foreach loop to print out the remaining lines.

These methods all can remove blank lines, but which one to choose depends on your needs and personal preferences.

bannerAds