I would like to use file locking on yaml files, but how do I get a file handle for the yaml file?
#!/usr/bin/perl
use strict;
use YAML::Syck;
use Fcntl ':flock';
use warnings;
my $cfg = YAML::Syck::LoadFile('t.yaml');
# need a handle
flock($fh, LOCK_EX) or die "couldn't get lock: $!\n";
$cfg->{a} = 1;
close $fh;
Update
Based on the answers I have now tried the following, but it always writes an empty invalid yaml file.
#!/usr/bin/perl
use strict;
use YAML::Syck;
use Fcntl ':flock';
use warnings;
open my $fh, ">t.yaml";
my $cfg = YAML::Syck::LoadFile($fh);
flock($fh, LOCK_EX) or die "couldn't get lock: $!\n";
$cfg->{a} = 1;
my $yaml = YAML::Syck::Dump($cfg);
$yaml::Syck::ImplicitUnicode = 1;
print $fh $yaml . "---\n";
close $fh;
Note that according to its documentation
LoadFilealso accepts filehandle. You can open first,flockand pass handle toLoadFile.Edit: I would use something like this: