|| die "File not found";
####
|| die "Unable to open input file: $!";
# ... and ...
|| die "Unable to open output file: $!";
####
use strict;
use warnings;
use File::Temp;
use File::Copy qw(move);
use Fcntl qw(:flock);
my $target_file = 'generic_bist_ctrl_defines.sv';
{
open my $in_fh, '<', $target_file or die "Cannot open input file: $!\n";
flock $in_fh, LOCK_EX | LOCK_NB or die "Cannot obtain a lock on $target_file: $!\n";
my $temp_out = File::Temp->new(TEMPLATE => "$0-$$-XXXXX");
while (my $line = <$in_fh>) {
$line =~ s/=131/= $a/g; # Did you actually mean $line =~ s/=(131)/= $1/g; ???
print $temp_out $line;
}
close $in_fh or die "Failed to close $target_file. Aborting. $!\n";
$temp_out->flush;
eval {
move($temp_out->filename, $target_file);
} or do {
warn "Failed to swap $temp_out into $target_file: $!\n";
# There may need to be more cleanup here, or possibly a die is more appropriate.
};
} # $temp_out falls out of scope; temp file should be removed even if the move call failed.
# flock falls out of scope; lock is released on $target_file.
####
use strict;
use warnings;
use Fcntl qw(:flock);
use Tie::File;
my $target_file = '.....';
{
my ($tied, @file_content)
$tied = tie @file_content, 'Tie::File', filename or die "Unable to tie $target_file: $!\n";
$tied->flock(LOCK_EX|LOCK_NB) or die "Cannot lock $target_file. Aborting. $!\n";
foreach my $line (@file_content) {
$line =~ s/foo/bar/;
}
} # $tied falls out of scope. File is closed, lock expires.