Update: danger++ made some excellent improvements.
As has already been hinted, at put a
my $do_trun; at the top of the routine.
use strict and warnings to avoid such problems in the future.
Also, I want to point out something else:
if ($fn =~ /^>[^>]/) obviously expects the string to already have the angle brackets embedded. But then you go and add some more in
$result = open($fh, ">$fn"); and
$result = open($fh, ">>$fn");
And while not detrimental, they shouldn't be in
sysopen($fh, $fn, O_CREAT | O_WRONLY); either. Together with the also already suggested removal of your
fatal_error calls, I suggest the following:
sub safe_open {
my $fn = shift;
# you need not initialize $fh anymore in Perl >= 5.6
my ($fh, $mode, $result, $do_trun);
$fn =~ s/^(>>?)//;
$mode = length($1);
if ($mode == 1) {
# write mode
if($flock_enabled) {
$do_trun = 1;
$result = sysopen($fh, $fn, O_CREAT | O_WRONLY);
}
else {
$result = open($fh, ">$fn");
}
}
elsif ($mode == 2) {
# append mode
$result = open($fh, ">>$fn");
}
else {
# read mode
$result = open($fh, $fn);
}
$result or die "Couldn't open $fn: $!";
flock($fh, 2) or die "Couldn't flock $fn: $!" if $flock_enabled;
truncate($fh, 0) or die "Could not truncate file $fn: $!" if $do_t
+run;
return $fh;
}
____________Makeshifts last the longest.
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.