Home : General : Perl Programming :

General: Perl Programming: Deleting a line from file.: Edit Log

Here is the list of edits for this post
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

Edit Log: