Where to start. First, what you are trying to do is invalid. Unless you have fixed length records, it is not possible to insert a record into the middle of a text file. That is the case regardless of the language. The best you can do is to read a file then write out to a different one, inserting the new record in the correct place in the new file.
Opening a file for append and read will position the current file position to end-of-file, so you will not read anything.
The
open statement requires parentheses around the argument list when you use the high precendent || operator. Or use the low precedence
or.
print on its own writes to STDOUT, not to a file.
By convention, it is not a good idea to use UPPERCASE for your own variable names, like $NAMES.
This may get you what you want:
#!/usr/bin/perl
use strict;
use warnings;
my $infile = '/home/yanni/scripts/testfiles/list_names';
my $outfile = "$infile.tmp";
open (my $in, '<', $infile ) || die "Can't open $infile $!\n";
open (my $out, '>', $outfile) || die "Can't open $outfile $!\n";
while (<$in>)
{
print $out $_;
if ($.== 3) {print $out "Simon\n";}
}
close ($in);
close ($out);
rename ($outfile, $infile) || die "Unable to rename: $!";
Update: On second thought, the record length has nothing to do with it if you want to insert (I was thinking of an overwrite). You would still have to read the records in first somehow.
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.