in reply to Re^3: In place search and replace with a hash
in thread In place search and replace with a hash
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 |