It's reasonable to assume that
vit would figure this out, but maybe it's worth mentioning that in order for "myOpen" to work, the existing code has to switch to using lexically scoped file handles (if it is not doing so already), and the existing open() calls have to change from whatever syntax has been used so far to exactly this syntax (moving the file handle out of the arg list, and making sure that mode and pathname are separate args):
my $fh = myOpen( "<", $pathname )
(with an added "or die ...", as appropriate)
Also, I was curious why you bother to localize $/, given that you are calling sysread, which doesn't use $/ at all. And when doing sysread, it would be good to check the return value more carefully -- zero means total failure, but any value other than the size of the file would mean a partial failure, which would probably be just as bad:
my %cache;
sub myOpen {
my( $mode, $path ) = @_;
my $fh;
if ( not exists $cache{ $path } ) {
-s $path or return; # don't do a 0-length or non-existent f
+ile
open $fh, $mode, $path or return;
( sysread( $fh, $cache{ $path }, -s _ ) == -s _ ) or return;
close $fh;
}
open $fh, $mode, \$cache{ $path } or return;
return $fh;
}
(updated to include the whole subroutine with a simplified conditional block, added the check for non-zero return from "-s", and removed an unnecessary "$size" variable)
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.