in reply to Deleting a record from a flat text file

Perhaps if you can show us the full code that deletes the file, that would help. Sometimes monks will give you a whole program for nothing, sometimes they won't. Typically, some up front work is encouraged.

As for solving your problem there are several ways to go about it. How large is the typical file? How large is it likely to get? You can simply write the good records to a new file and rename it to the old one (which would take less memory if you have a big file), or you could read the entire file, only sticking good records into an array and then write that array back out to the file after you have truncated it at the beginning. However, these and other strategies can be dependent upon your requirements.

Cheers,
Ovid

New address of my CGI Course.
Silence is Evil (feel free to copy and distribute widely - note copyright text)

  • Comment on Re: Deleting a record from a flat text file

Replies are listed 'Best First'.
Re: Re: Deleting a record from a flat text file
by mikael-g (Initiate) on Jun 13, 2003 at 15:12 UTC
    the code is as follows .... i have a problem to build the the second part with the first, to write back ,...
    #!/usr/bin/perl # e_id="10.20"; # # open (DATABASE, "mybase.txt"); while (<DATABASE>) { $row = $_; chop $row; ($id2, $status, $fromemail, $efrom,) = split(/\|/, $row); if ($form{'e_id'} ne $id2) {$new_row .= "$row\n";} } close (DATABASE); #writing the '$new_row' to the textfield:<p> open (DATABASE, ">mybase.txt"); print DATABASE "$new_row"; close (DATABASE);

    edited: Sat Jun 14 14:05:07 2003 by jeffa - code tags

      You have commented out the first call to open which means the mybase.txt is not being read. Then you clobber the file with your second open.

      Couple of things I'd point out. Always, always, always, check the return value of open, you'll save yourself a lot of grief:

      open(DATABASE, "mybase.txt") || die "open mybase.txt - $!\n";
      Try not to use chop to remove newlines, use chomp instead. chop will remove (and return) the last character in the string regardless of whether it's a newline or not.

      -- vek --
      A few things you might want to consider.

      If you're going to be using this script often you might want to use a command line argument for your pattern matching, and you might want to save a copy of the file you're editing to avoid any unpleasant errors (like deleting the whole file). Just a thought.

      -muoyo