I have two files: one with text and the other with key / hash values. I want to replace key occurrences with hash values. The following code does this, which I want to know if there is a better way than using the foreach loop that I use.
Thank you all
Edit: I know this is a little weird using
s/\n//; s/\r//;
instead of chomp, but this works with files with mixed end-of-line characters (edited on both windows and linux) and chomp (I think) doesn't.
File with key / hash values ββ(hash.tsv):
strict $tr|ct warnings w@rn |ng5 here h3r3
File with text (doc.txt):
Do you like use warnings and strict? I do not like use warnings and strict. Do you like them here or there? I do not like them here or there? I do not like them anywhere. I do not like use warnings and strict. I will not obey your good coding practice edict.
Perl script:
#!/usr/bin/perl use strict; use warnings; open (fh_hash, "<", "hash.tsv") or die "could not open file $!"; my %hash =(); while (<fh_hash>) { s/\n//; s/\r//; my @tmp_hash = split(/\t/); $hash{ @tmp_hash[0] } = @tmp_hash[1]; } close (fh_hash); open (fh_in, "<", "doc.txt") or die "could not open file $!"; open (fh_out, ">", "doc.out") or die "could not open file $!"; while (<fh_in>) { foreach my $key ( keys %hash ) { s/$key/$hash{$key}/g; } print fh_out; } close (fh_in); close (fh_out);
h.mon source share