Shaun Fryer wrote:
>
> I'm writing an app which uses a flat file to store a
> *short* list of simple key/value pairs. However having
> read the flock() man page, I'm unsure about whether I
> need to seek() in cases where I'm not merely appending
> to the file (such as when deleting a record).
>
> sub Delete_Record {
>     my ($file, $key, $value, @array) = @_;
>     open(OUT, ">$file");
>     flock(OUT, LOCK_EX);
>
>     seek(OUT, 0, 0); # Should I do this?
>
>     foreach (@array) { # FYI: $/ = "\n"
>
>         seek(OUT, 0, 2); # Or perhaps this?
>
>         print OUT $_ unless ( m/^$key\s+$value$/ );
>     }
>     flock(OUT, LOCK_UN);
>     close(OUT);
> }
>
> Btw, the above code is just to illustrate the question,
> thus no error checking and so forth.

Hi Shaum.

No. There's no call to 'seek' required at all. Your 'open'
statement opens a brand new stream into an empty file so
all your output will be written in sequence from the beginning
of the file.

However I would rather see it written in a different way, with
the array as the 'master' copy of the data which is then
flushed to disk when required. Something like the code below.

Also note that you need to pass the array by reference otherwise
you can't manipulate its data within the subroutine.

HTH,

Rob



sub Delete_Record {

  my ($key, $value, $array) = @_;

  my $i = 0;

  foreach (@$array) {
    if ( /^$key\s+$value$/ ) {
      splice @$array, $i, 1;
      last;
    }
    $i++;
  }
}

sub Flush_Data {

  my ($file, $array) = @_;

  open(OUT, ">$file");
  flock(OUT, LOCK_EX);

  foreach (@$array) {
    print OUT $_;
  }

  flock(OUT, LOCK_UN);
  close(OUT);
}






-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to