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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.