Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Safe way to open files

by Aristotle (Chancellor)
on Jun 15, 2002 at 15:33 UTC ( #174846=note: print w/replies, xml ) Need Help??

in reply to Safe way to open files

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://174846]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2021-06-20 21:02 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (95 votes). Check out past polls.