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
Subject Author Views Date
Thread Deleting a line from file. zeshan 3629 May 25, 2003, 7:44 PM
Post Re: [zeshan] Deleting a line from file.
Paul 3416 May 25, 2003, 11:43 PM