2つのファイルがあります。1つはテキストを含み、もう1つはキー/ハッシュ値を含みます。キーの出現箇所をハッシュ値に置き換えたい。次のコードはこれを実行します。私が知りたいのは、使用している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);