I want to replace a set of strings across multiple files. Ideally, I want to change the files in place. I have a hash where the keys are the strings to find, and the values are the strings to replace them with.
So something like s/$key/$hash{$key}/g. Below is my code to build the hash and to search files for the hash keys and replace them with the associated hash values. The errors are included at the end. I ensured that the hash is working, and I have tested that my regex is correct as well.
open my $fh, '<', 'hash.txt' or die "Can't open file $!"; LINE: while (my $line = <$fh>) { my ($key, $value) = split /\s/, $line; next LINE if not $key; $hash{$key} = $value; chomp (%hash); } close $fh; @file_array =<*.txt> or die $!; foreach $file (@file_array) { open FH, "$file", or die $!; while (<FH>) { if (/(\S+):(\S+).*\n/) { s/$1/$hash{'$1'}_$2/g; } } close FH; }
The s/foo/bar/g itself is not working (I tried s/$1/$2/g), and I have never done a find and replace in place before. I am getting two "use of uninitialized value" errors:
Use of uninitialized value $hash{"$1"} in concatenation (.) or string at test_perl.pl line 29, <FH> line 5.
Use of uninitialized value $2 in substitution iterator at test_perl.pl line 30, <FH> line 5.
I get these errors once for every line in FH where the search pattern is found.
Thanks for reading!
In reply to In place search and replace with a hash by hkates
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |