Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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.

In reply to Re: Safe way to open files by Aristotle
in thread 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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2021-06-18 06:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (88 votes). Check out past polls.

    Notices?