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.