-
- 前回のサブルーチンだとパターンを複数指定できるのだが、パターンが重複する場合(例: abc => "ab", ab => "abcd"など)後から指定したもので書き換えられてしまうことが考えられる。しかもこれはハッシュから取得しているためどの順番で書き換えられるがわからない。バグの元にも成りかねないのでひとつだけ指定する、と変更した。そもそも正規表現パターンを動的に使用しているので扱いには注意が必要。
sub okikae
{
my ($infile, $outfile, $hash) = @_;
goto ERROR if scalar keys %$hash;
my ($ptn) = keys %$hash;
if (sysopen my $fh, $infile, O_RDONLY) {
my ($fh_tmp, $tmpfile) = tempfile(UNLINK => 1);
while (my $line = <$fh>) {
chomp $line;
if ($line =~ /$ptn/) {
$line = "$hash->{$ptn}";
}
print $fh_tmp $line . "\n";
}
close $fh;
close $fh_tmp;
unless (rename $tmpfile, $outfile) {
print "rename err $tmpfile, $outfile $!\n";
goto ERROR;
}
}
else {
print "sysopen err infile $!\n";
goto ERROR;
}
return 1;
ERROR:
return 0;
}