use strict; use warnings; use Fcntl ':flock'; # Import LOCK_* constants sub getFile { my $fileName = shift(@_); unless (defined $gotFiles->{$fileName}) { local $/; open(my $fh, '<', $fileName) or die; flock($fh, LOCK_SH) or die; $gotFiles->{$fileName} = <$fh>; # File handle automatically closed and unlocked here. } return $gotFiles->{$fileName}; } sub writeFile { my $data = shift(@_); my ($filename) = $data =~ m@(.*?)@s or return 0; my ($filedata) = $data =~ m@(.*)@s or return 0; { open(my $fh, '>', "$ENV{DOCUMENT_ROOT}/$filename") or return 0; flock($fh, LOCK_EX) or return 0; print $fh $filedata; # File handle automatically closed and unlocked here. } $gotFiles->{"$ENV{DOCUMENT_ROOT}/$filename"} = $filedata; return 1; }