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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.