Gossamer Forum
Home : General : Perl Programming :

Deleting text from text files in PERL

Quote Reply
Deleting text from text files in PERL
Say if I have a list of names in a text file, like this (Bob, Bill, Steve, Sam, ) and I want to delete "Bill, ". How do I do that?
Quote Reply
Re: [Netherless] Deleting text from text files in PERL In reply to
How big is your file (the size will depend on which code I show you :) )
Quote Reply
Re: [Paul] Deleting text from text files in PERL In reply to
Oh, I dunno. It's for a chatbot I'm making--a friendslist, to be precise. I want to add and delete names on the list with just a simple command. I have that part figured out, but all I need now is the code to find the username that I have specified, and if it's on the list, delete it. For example: '!defriend Joe456' --> Look for Joe456 on Friends.TXT --> If found, delete name. That's all I need, nothing fancy, just a simple thing to delete stuff out of text files without having to manually edit the textfiles because that's a pain in the butt. Tongue
Quote Reply
Re: [Netherless] Deleting text from text files in PERL In reply to
grep..

open THISFILEHANDLEISSOLONG, "<friends.txt";
my @list = grep {/^$name$/}, <THISFILEHANDLEISSOLONG>;
close THISFILEHANDLEISSOLONG;

open THISFILEHANDLEISSOLONG, ">friends.txt";
print THISFILEHANDLEISSOLONG join ("\n", @list) . "\n";
close THISFILEHANDLEISSOLONG;

.. you can change the filehandle.
Quote Reply
Re: [widgetz] Deleting text from text files in PERL In reply to
>>
my @list = grep {/^$name$/}, <THISFILEHANDLEISSOLONG>;
<<

That will never match, as each line will have a newline at the end and you are trying to match ^SomeName$, but you'd want something like this in any case:

my @list = grep { ! /^\Q$name\E\n$/ }, <THISFILEHANDLEISSOLONG>;

...to only match the ones you want, not the one's you don't want. From the first post it looks like the names are in a comma delimited list, not one per line anyway.

If your grep did match (which it won't), using join "\n", @array will then you leave you with blank lines all through your file.

Slurping into an array is also not a good idea if your file is faily lengthy.

Edit: You'll certainly want to use flocking too unless you like fixing corrupt databases.

Last edited by:

Paul: Jul 30, 2002, 6:58 AM
Quote Reply
Re: [Paul] Deleting text from text files in PERL In reply to
It would probably be best to chomp the newlines instead of trying to match for them.

- wil
Quote Reply
Re: [Wil] Deleting text from text files in PERL In reply to
"best" in what way?....if you chomp them you are just going to have to put them back anyway. You may as well leave them in and do:

print FILEHANDLE @array;

Last edited by:

Paul: Jul 30, 2002, 7:47 AM