Perl open(). Inserting data into a file

D

dshan

Hi all!

I'm a Perl newbie. My question is: how do I insert data contained in
$string at a certain position in a file? I tried to use

open(OUT,"+< $out") or die "Can't read/write $out: $!";
while(<OUT>) {
if($_ =~ /<add_here \/>/s) { print OUT $string; }
}

to insert new data into an XML file which looks like this:

<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info</info>
<info>Some Info 2</info>
....
<add />
</disc>

but on update it prints the following:

<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info</info>
<info>Some Info 2</info>
....
<add_here />
</disc>
<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info 1</info>
<info>Some Info 2</info>
....
<add_here />
</disc>
<info>Some Info 3</info>

that is, it appends the preceding data and the new data ($string) at
the end of the file. Why? I just want to add new text at the <add_here>
position...

Regards,
dshan
 
J

Jürgen Exner

I'm a Perl newbie. My question is: how do I insert data contained in
$string at a certain position in a file? I tried to use [...]

Your Question is Asked Frequently, please see 'perldoc -q "insert a line"':

"How do I change one line in a file/delete a line in a file/insert a
line in the middle of a file/append to the beginning of a file?"

jue
 
J

Julia De Silva

I'm a Perl newbie. My question is: how do I insert data contained in
$string at a certain position in a file? I tried to use

open(OUT,"+< $out") or die "Can't read/write $out: $!";
while(<OUT>) {
if($_ =~ /<add_here \/>/s) { print OUT $string; }
}

to insert new data into an XML file which looks like this:

<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info</info>
<info>Some Info 2</info>
...
<add />
</disc>

but on update it prints the following:

<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info</info>
<info>Some Info 2</info>
...
<add_here />
</disc>
<?xml version="1.0" encoding="Windows-1251"?>
<disc>
<info>Some Info 1</info>
<info>Some Info 2</info>
...
<add_here />
</disc>
<info>Some Info 3</info>

that is, it appends the preceding data and the new data ($string) at
the end of the file. Why? I just want to add new text at the <add_here>
position...

Regards,
dshan

This is a FAQ. In fact it is more than frequently asked !!
FAQ 5 How do I change one line in a file/delete a line in a file/insert a
line in the middle of a file/append to the beginning of a file?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top