barring any syntax errors:
use Fcntl qw(:DEFAULT :flock); open (MYFILE1, "<", "$file") or sysopen (MYFILE, "$file", O_RDONLY) or die "$!"; flock (MYFILE1, LOCK_SH) or die "$!"; chomp (@input=<MYFILE>); close MYFILE1; # pretending you then did your work on the input, split at the ":" # and stuck the results back into @output... open (MYFILE2, ">", "$file") or sysopen (MYFILE, "$file", O_WRONLY) or die "$!"; flock (MYFILE2, LOCK_EX) or die "$!"; foreach $item(@output){ print MYFILE2 "$item"."\n";} close MYFILE2;

doing the double open-sysopen technique helps avoid races for opening the file and having that content altered in those few miliseconds.

it's rare, if you have a small site, that two users would access the file at the same time - but i wouldn't take the risk. Besides, w/CGI work - if someone is ~intentionally~ messing w/your system -> you want to ensure that you're opening the right data and not something that was swapped in by a nefarious user. (This is the reason for using 2 separate filehandles too -> MYFILE1 and MYFILE2).

LOCK_EX (exclusive locks) are needed, when writing to files - otherwise, LOCK_SH (shared locks) are all that's needed, i believe, when reading.

also: i'm not sure, if i'd actually use DIE like this in a cgi system, if the user is going to see the output. You probably want to 'die' gracefully -> using WARN, &subroutine, or some other action instead.

for more info - see Camel -> pgs 419-422, 571-573, 712, 714-715, 808-810


In reply to Re: How to modify/delete records in a flat-file database? by wolfi
in thread How to modify/delete records in a flat-file database? by JoeJaz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.