Several problems arise from the code. The first - scalability - reading a whole file into an array is kinda asking for trouble, you might run out of memory, and it'll probably take a longer while.
Another is that you're opening the temporary file for appending. Assuming the file is new, this shouldn't matter to you, but if a file by that name exists, you just added the new text to it's end, instead of rewriting from scratch. See perlopentut for a tutorial on openning files.
Yet another, which directly confronts your problem, is that the readline operator does not remove the input record seperator ($/, which is usually "\n") from read lines.
reading a file which contains "foo\nbar\n" into an array will yield ("foo\n","bar\n").
When you join $_ with your string, it'll keep the line break you put in, making $_ contain two lines.
To get around that line break you need to use chop, which takes off the last character of a string, or chomp which only removes an occurance of $/ from a string.
I think the wisest approach would be something like this:
open (FILE,"external_file.txt");
open (TEMP,">external_file.txt.tmp");
my $i = 0;
while (<FILE>){ # magical - puts every line in $_, until the end of fi
+le is reached
if ($i == 3){ # if $i is the 3rd line
chomp $_; # remove the line break at the end of $_
$_ .= "my new line goes here\n"; # add the string
}
print TEMP $_; # print the line you just read to the temporary fil
+e
} continue { # performed at the end of every loop iteration
$i++;
}
close FILE;
close TEMP;
unlink ("external_file.txt"); # incase rename does not clobber, delete
+ the original
rename ("external_file.txt.tmp","external_file.txt");
-nuffin
zz zZ Z Z #!perl
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.