Removing empty lines from a file The below code removes empty line from test.txt. I posted this answer on StackOverflow but someone commented that this code needs review and suggested me to post here. Please post your comments!

use strict;
use warnings;

my $file = "test.txt";
 open (FH, "+&lt; $file");
my @lines = ();
my $i = 0;
while (&lt;FH&gt;)
{
    if ( m/^\s*$/ )
    {
        print "Found an empty line\n";
    }
    else
    {
        $lines[$i] = $_;
        $i++;
    }
}
close FH;
open (FH, "+&gt; $file");
print FH @lines;
close FH;
Don't indent the open line differently to the surrounding lines.

Always check the result of open, or use autodie.

Why do you use the + modes to open the file? Just use plain &lt; and &gt; if you don't need to read and write, respectively.

Don't use bareword filehandles, use variables:

open my $fh, '&lt;', $filename or die $!;


There's no need to use the variable $i, you can just push to the array.

If the input file is very large, your code could run out of memory. You don't need to store all the lines in an array, you can print them to a different file and rename it to the original name at the end.