Link to home
Start Free TrialLog in
Avatar of kudak
kudak

asked on

deleting data in text file

well, i have a homepage whereby users can key in data and that data will automatically be in my text file. i use pipe and the sample of the text file is like this:

aa|bb|cc|dd
ee|ff|ggg|fdg
rr|fdg|tfh|fcbv

from the web, user has to enter for fields, and that data will be inserted in the text file as above. it's working as what i wanted.
the problem is when i want to delete let's say the second row, how could i do it? can i do so? should i replace that row to blank? is there any delete command in perl??
answer with coding is really appreciated.
bye
Avatar of Kim Ryan
Kim Ryan
Flag of Australia image

It's a common question and has been covered in the Perl FAQ:
http://www.perl.com/pub/doc/manual/html/pod/perlfaq5.html#How_do_I_change_one_line_in_a_fi
Avatar of cadabra
cadabra

You will need a synchronization mechanism, to serialize access to the file;

See Win32::Mutex , if you are using activestate perl (on windows platform).
ASKER CERTIFIED SOLUTION
Avatar of TYoung
TYoung

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kudak

ASKER

ok tyoung. let's say i that data is keyed in by the user. is it going to be

open(FILE, "file.txt");
my(@lines) = <FILE>;
close(FILE);

$LineToDelete = '(FORM{name} eq "xx") && (FORM{address} eq "zz"';

$Numbs = @lines;

open(FILE, ">file.txt");
     for($i = 0; $i < $Numbs - 1; $i++) {
          print FILE @lines[$i] unless ($i = ($LineToDelete - 1));
     }
close(FILE);

thanks.


Okay, then you would want something like this:

open(FILE, "file.txt");
      my(@lines) = <FILE>;
close(FILE);
my($i) = 0;
foreach (@lines) {
      $FILELINES{$_} = $i + 1;
      $i++;
}
my($LTD) = $FORM{'name'} . "|" . $FORM{'address'} . "\n";
$LineToDelete = $FILELINES{$LTD};
$Numbs = @lines;
open(FILE, ">file.txt");
     for($i = 0; $i < $Numbs - 1; $i++) {
          print FILE @lines[$i] unless ($i = ($LineToDelete - 1));
     }
close(FILE);

Again.. this is untested...
how about using grep() to remove the unwanted lines from @lines ...
If you use grep, you may delete some line of a person that has the same first name, or same zip code, or something like that.
Avatar of ozo
#You could grep for the same condition you're testing in your for loop
#or
{local $^I=$$; local @ARGV=("file.txt");
while( <> ){ print unless /^\Q$FORM{name}|$FORM{address}|\E/ }
}