In my script, i am touching a file to read, append and rewrite one right after the other. I am also locking the file each time I touch it and unlocking it once I am done with the read. I dont think this is a rarity in scripts, so I am assuming once again that not only is there more than one way to do it, but there is probably and more resourceful way of doing it.

sub add { open FH, ">>$file" or die "Cant open config file $!\n"; &lock(*FH); print FH "zone \"$formdata{domain}\" in \{\n\ttype slave\;\n\tfile\" +$client\/ db.$formdata{domain}\"\;\n\tallow-query \{ any\; \}\; \}\;\n\n"; &unlock(*FH); close FH; open FH, "$file" or die "Could not open $file : $!\n"; &lock(*FH); $/ = "\;\n\n"; my @array = <FH>; @array = sort @array; &unlock(*FH); close FH; open FH, ">$file"; &lock(*FH); print FH @array; &unlock(*FH); close FH; $/ = "\n"; }

I guess I have two main questions. First, do I need to lock and unlock the files with each open statement? or can I do this once at the beginning and then unlock at the end of the three procedures? I read over flock but didnt get a good feel of whether or not the statement could include multiple open and closes before an unlock statement was set.
And finally, does this process really need to have "$file" ">>$file" and ">$file"? I can't come up with other methods that work, so I offer it up for your advice.

humbly -c


In reply to Opening the same file over and over. Shorter way to do this? by c

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.