Thanks for this very useful post. I would just like to add that you don't have to override CORE::GLOBAL::open, etc. Instead, you can override open and close in only the current package:
use subs 'open'; sub open (*;$@) { print "Open sesame!"; #Need logic as Dave outlined for calling CORE::open return CORE::open [...]; } open my $fh, '>file.txt' or die "Ouch!";

This will solve one of the problems you mentioned, as now you are not overriding modules' use of open and close.

The problem of lock failing wouldn't really be a problem as long as you handled it properly in your open function--just catch any errors there and close the filehandle if lock fails.

The problem of seeking to the end of the file would be pretty easy to handle as well: detect that the file was opened for appending, and only seek to the end if that is true.

Still, I do tend to think that this solution is more hacky than it's worth. Overriding system functions is not really recommended. It makes for confusing code, and there still may be unintended side effects.

I think space_monk's suggestion of making your own, differently named, open and close functions that lock and using them where needed would be easier overall.



When's the last time you used duct tape on a duct? --Larry Wall

In reply to Re^2: Auto flock by ColonelPanic
in thread Auto flock by AlfaProject

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.