I don't like this for the following reasons:
- You are reading the whole file in memory TWICE! Once for
the arguments to the foreach and another one when pushing
everything into @data. In any case, you want to use while
instead of foreach.
- You are overwriting the file in place, without creating
a backup. What if the machine crashes in the middle of the
"print FILE @data"? You have lost your data.
I personally like the technique of writing the results to
a new temporary file, and then renaming the original to a
backup name and the temporary file to the original. Something
like this:
open FILE, "/path/to/file" or die "$!\n";
open OUT, "/tmp/tmpfile.$$" or die "$!\n";
while(<FILE>) {
next if /^\s*$/;
print OUT, $_;
}
close FILE; close OUT;
rename("/path/to/file", "/path/to/file.bak")
or die "Error in rename: $!\n";
rename("/tmp/tmpfile.$$", "/path/to/file")
or die "Error in rename: $!";
Side note: using "/tmp/tmpfile.$$" as a temporary file
name could have security implications if the program is running
set-uid. For better ways of creating a temporary file name,
see the FAQ
How do I make a temporary file name?
Also, a regex is not necessary if you are looking for strictly
empty lines. But many times, a line is considered empty even
if it contains white space, in this case using regular expressions
is the best way to do it.
--ZZamboni