I'm developing a script and want to create a sub that'll open files safely at all times. Below I've posted the sub I'm currently using which seems to be working okay except once in a blue moon a file will go to zero bytes totally randomly with no explanation. I've narrowed the problem down to something in this sub but I can't seem to find what is exactly causing it... so I've come to seek help :) Also, in the below snippet $flock_enabled will either equal 1 or 0 depending on if flock is enabled on the users system or not.

This sub would be used like: my $filehandel = safe_open("some.file"); and the sub fatal_error has nothing more then this in it: my $error = shift;print "content-type: text/html\n\n$error";exit;
sub safe_open { my $fn = shift; my $fh = do { local *FH }; my ($mode, $result); if ($fn =~ /^>[^>]/) { $mode = 1; } elsif ($fn =~ /^>>/) { $mode = 2; } if ($mode == 1 and $flock_enabled) { # Write mode with flock. $do_trun = 1; $result = sysopen($fh, $fn, O_CREAT | O_WRONLY); } elsif ($mode == 1) { # Write mode without flock. $result = open($fh, ">$fn"); } elsif ($mode == 2) { # Append mode. $result = open($fh, ">>$fn"); } elsif (!$mode) { $result = open($fh, $fn); } unless ($result) { # Open failed. fatal_error("Couldn't open $fn."); } flock($fh, 2) if $flock_enabled; truncate($fh, 0) or fatal_error("Could not truncate file $fn.") if + $do_trun; return $fh; }
Thanks!

Edit kudra, 2002-06-15 Added READMORE


In reply to Safe way to open files by L0rdPhi1

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.