Gossamer Forum
Home : General : Perl Programming :

Deleting a line from file.

Quote Reply
Deleting a line from file.
Code:
#!/usr/bin/perl -w
$delete = "he";
$infile="bar.txt";
$outfile="shift.txt";
open (IN, "$infile");
open (OUT, ">$outfile");
@temp=<IN>;
foreach $line (@temp) {
if($line !~ m/^$delete/i)
{
print OUT $line;
}
}
close (IN);
close (OUT);

exit;

The above code is working fine, no problems in it.

What I needed is to write the output to same file.
Means after deleting the desired lines, the IN file should be re-written rather than creating a new OUT file.

So I made the following modification to it.

Code:
#!/usr/bin/perl -w
$delete = "he";
$infile="bar.txt";
$outfile="shift.txt";
open (IN, "$infile");
open (OUT, ">$outfile");
@temp=<IN>;
foreach $line (@temp) {
if($line !~ m/^$delete/i)
{
print OUT $line;
}
}
close (IN);
close (OUT);

unlink ($infile);

rename ($outfile, $infile);

exit;

But I don't know why I am not satisfied with modification, however its working fine too. Just want to confirm are there any other ways to do the same??

Any better options?

Thanks,

Zeshan.

Thanks,

Last edited by:

Wil: May 26, 2003, 3:03 AM
Quote Reply
Re: [zeshan] Deleting a line from file. In reply to
http://www.perldoc.com/....0/lib/Tie/File.html