in reply to Re^3: In place search and replace with a hash
in thread In place search and replace with a hash

Ah, thank you! I don't know why I was trying to use "_". Totally unnecessary. Now that you have helped me to fix most of these basic problems, I am back to the original problem of replacing the hash keys with the hash values. The hash is created with:
use strict; use warnings; open my $fh, '<', 'hash_test.txt' or die "Cant open file $!"; LINE: while (my $line = <$fh>) { my ($key, $value) = split /\s/, $line; next LINE if not $key; $hash{$key} = $value; chomp (%hash); while ( my( $key, $value ) = each %hash ) } close $fh;

Then the hash keys are searched for (and replaced with their associated values if found) in the input file using

open FH, "<infile.txt" or die $!; open OUT, ">outfile.txt"; while (<FH>) { if (/(\S+):(\S+).*\n/) { $var1 = "$1"; $var2 = "$2"; print OUT "$hash{$var1} $var2\n"; } elsif (/(.*)\n/) { print OUT "$1\n"; } } close FH;

This results in the error

Use of uninitialized value within %hash in concatenation (.) or string at test_perl.pl line 41, <FH> line 5

UPDATE I think the problem was that I had initialized my %hash inside a while loop. I moved it up to the beginning of the program, and it worked!

Replies are listed 'Best First'.
Re^5: In place search and replace with a hash
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 05:33 UTC
    ... back to the original problem of replacing the hash keys with the hash values.

    You say you know your translation hash is being built properly, so since I'm about to turn into a pumpkin, let me leave you with the following code to think about:

    Play with it and get the substitutions right, and you can move on to the business of writing the edited file tomorrow.


    Give a man a fish:   <%-(-(-(-<