M
Matija Papec
I thought this could be usefull to someone but before you use it bear in
mind its limitations,
- probably works as expected only on Linux and other *nix like systems
- only convenient for text files
- handling very large files is not efficient
- if it isn't there, file gets created (this is a feature actually)
- ?
Function can be used in two ways, I generally use second for log files and
first for all other purposes..
#1) managing whole file at once
my @txt;
my $fh = OpenLock('/tmp/testing.txt', \@txt);
print $fh "top line\n", @txt;
close $fh;
#2) append lines to file
my $fh = OpenLock('/tmp/testing.txt');
print $fh "bottom line\n";
close $fh;
sub OpenLock {
###############################################################
#
# open rw, flock, fill @$ra, truncate file to zero, return FH
#
###############################################################
my($file, $ra) = @_;
local *FH;
open FH, "+>>$file" or die $!;
flock(FH, 2); #exclusive_lock
if ($ra) {
seek(FH, 0, 0);
@$ra = <FH>;
seek(FH, 0, 0);
truncate(FH, 0);
}
return(*FH);
}
mind its limitations,
- probably works as expected only on Linux and other *nix like systems
- only convenient for text files
- handling very large files is not efficient
- if it isn't there, file gets created (this is a feature actually)
- ?
Function can be used in two ways, I generally use second for log files and
first for all other purposes..
#1) managing whole file at once
my @txt;
my $fh = OpenLock('/tmp/testing.txt', \@txt);
print $fh "top line\n", @txt;
close $fh;
#2) append lines to file
my $fh = OpenLock('/tmp/testing.txt');
print $fh "bottom line\n";
close $fh;
sub OpenLock {
###############################################################
#
# open rw, flock, fill @$ra, truncate file to zero, return FH
#
###############################################################
my($file, $ra) = @_;
local *FH;
open FH, "+>>$file" or die $!;
flock(FH, 2); #exclusive_lock
if ($ra) {
seek(FH, 0, 0);
@$ra = <FH>;
seek(FH, 0, 0);
truncate(FH, 0);
}
return(*FH);
}