Home: Perl Programming Help: Intermediate:
Add multiple lines to a file


Oct 6, 2001, 10:05 AM

Views: 796
Add multiple lines to a file

How to add multiple extra line to a file.
Not at the beginning, not at the end but somewhere between that?

The following line I want to add:

$add_lines = qq~
This is a test\n
This is test 2\n
This is test 3\n

Those line have to be added after the following line:
$cat_id = *;
Where * stand for a number. (Can be 1,2,3,4 etc)
and for the following line:
# Output Layout for the product display

Can this be done?


Oct 7, 2001, 9:00 AM

Views: 785
Re: Add multiple lines to a file

If your file has fixed-length records, you can simply seek() to that location and print the codes. In your case however, it's a bit difficult. You can't goto a line since a text file is nothing but dump binary data (ie: 0101 0101 1010 1010 1110). How would you edit the Nth line then, and insert some code? A computer can't.

2 Solutions:

1. get the file into an array; my @Array = <FILE>; then, edit the array and write it back.
2. open the file, read through until you reached the line preferred (write the read lines into a temp. file). then write the new lines to the temp. file, and write the last lines from the original to the end of the temp. file. Then copy the file over the original file. A bit difficult, but recommended for large files.

Then again, if you're a great perl programmer, you know how to sysopen() the file with O_RDWR and then lock it. In this case you're file can't be overwritten, and the file copy will be less difficult (just seek() to the beginning, truncate() to 0 length. Then print the data from the other file into the original).

This should be done like:

use Fcntl qw(:DEFAULT :flock); 

# Open original and temp
sysopen(FILE, $File, O_RDWR) or die $!;
flock(FILE, LOCK_EX);
open(TEMP, "$File.tmp") or die $!;

# Read through and test
while(my $Line = <FILE>)
.... is this the nth line? -> go out of the loop
print TEMP $Line;

# New data and remaining of <FILE>
print TEMP $YourNewData;
while(my $Line = <FILE>) { print TEMP $Line; }

# the re-open should be done better then this.
# In fact, be eleminated

# File copy
open(TEMP, "$File.tmp") or die $!;
seek(FILE, 0, 0) or die $!;
truncate(FILE, 0) or die $!;
print FILE <TEMP>;

# hehe

Hope it helps, and this code is bug free. (have typed it directly into the browser)