CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
deleting a line

 



QuestOFions
Deleted

May 17, 2000, 5:39 PM

Post #1 of 4 (382 views)
deleting a line Can't Post

I have a data file and I wanted to delete a line. How would I go about this? Thank You


darian
Deleted

May 18, 2000, 2:55 AM

Post #2 of 4 (382 views)
Re: deleting a line [In reply to] Can't Post

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

open(OUT, "file.txt") or die;
open(IN, "file.txt") or die;
while (<OUT> ) {
print IN $_ unless ($_ =~ $delete_line);
}
close(IN);
close(OUT);</pre><HR></BLOCKQUOTE>

This should do what you want. Not sure if I have it perfect as I am a bit of rusty right now. Been working with VB to much as of late. Smile


Cure
User

May 18, 2000, 7:11 AM

Post #3 of 4 (382 views)
Re: deleting a line [In reply to] Can't Post

open(IN,">>file.txt") or die $!;


Cure;


japhy
Enthusiast

May 18, 2000, 9:37 AM

Post #4 of 4 (382 views)
Re: deleting a line [In reply to] Can't Post

Ok, this is in the FAQ. It's also been answered before.

First, doing

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


open OUT, "file";
open IN, "file";
while (<OUT> ) {
print IN $_ unless $_ =~ $delete_line;
}
close IN;
close OUT;
</pre><HR></BLOCKQUOTE>

will not do the job. You need to open IN for output (and "IN" and "OUT" are kinda backwards -- one would think you READ from "IN", and WRITE to "OUT"). But you can't make it output to the SAME FILENAME, or else that file will be truncated to 0, and your reading will not work.

I suggest Perl's BUILT IN in-place editing.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


{
local $^I = ".bak"; # keep a backup file
# make this "" if you don't want one
local @ARGV = ($filename);
while (<> ) {
print unless
$_ =~ /foo/ # don't print lines with "foo"
or
$. == 13; # don't print line 13
}
}
</pre><HR></BLOCKQUOTE>

To see the complete answer to this, please look at Perl FAQ 5.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives