G'Day Monks,

I'm working on some code that involves some heavy file I/O. There will be lots of open() and close() calls. The kicker is that every time I mess with file, there are going to be some other things I'm required to do (examples: file locking, reporting what files were opened when, notifying someone via some method, etc). So what I would like to do is create a subroutine that handles everything in one place. E.g. something like:
sub myopen { my ($file, $mode, $locktype) = @_; #open the file...for the sake of brevity #I'll not include the mode logic here if (open FH, "$file"){ print "Opened $file successfully.\n"; #lock the file #do whatever else needs to be done return *FH; } else { warn "Can't open: $!\n"; } }
That way any time I need to open a file, I can just call on this sub instead of doing open(), then flock(), then whatever else every single time.

The trouble is that this is broken. =) I wrote a simple little test script that just opens a couple of handles using something like the above. When I close any one of the handles, I suddenly get "Bad file descriptor" when trying to do anything with the other. I think you can see why. There's a duplicate handle name problem and a probably a scoping issue ("use strict" is a requirement for this code).

So is there a way to do this that actually works? Just off the top of my head, I wonder if it would be possible to do something like create a handle that is not associated with any file, pass that to the sub and have the sub use it in the open() call. But any solution would do.

Thanks!

In reply to Unassociated Filehandles and Subroutines by Anonymous Monk

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.