我有两个文件,一个带有文本,另一个带有键/哈希值。我想用哈希值替换键的出现。以下代码执行此操作,我想知道是否有比我正在使用的 foreach 循环更好的方法。
谢谢大家
编辑:我知道使用它有点奇怪
s/\n//;
s/\r//;
而不是 chomp,但这适用于具有混合行尾字符的文件(在 Windows 和 linux 上编辑)而 chomp(我认为)不适用。
带有键/哈希值的文件 (hash.tsv):
strict $tr|ct
warnings w@rn|ng5
here h3r3
带有文本的文件(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 脚本:
#!/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);