On Thu, 24 May 2001, David Blevins wrote:

> Thanks to everyone for the great input on my last question.  Here's another.
>
> There has to be a better way to modify/delete lines in a file than this.
>
>     my $filename = "thefile";
>     my $lineToDelete = "I'm a bad line, delete me.";
>
>     open(FILE, "< $filename");
>     open(FILE_TMP, "> $filename.tmp");
>
>     while(<FILE>){
>         next if /$lineToDelete/;
>         print FILE_TMP;
>     }
>
>     close(FILE);
>     close(FILE_TMP);
>     rename( "$filename.tmp", $filename);

That's one way to do it, and there's nothing wrong with this way (I will
note you should be testing for failure on your open and print statements).
You can also let Perl handle some of this temp file business by using the
-i and -p command-line options.  It handles the temp file manipulation for
you:

perl -pie 's/\cM//g' myfile

(see the perlrun docs for more info on this)

Alternatively, you can open the file, dump its lines into an array, pull
out the line you don't want, then write back out.  This is not a good idea
if the file is large, though.

-- Brett

Reply via email to