近頃版/another blog@hatena/Wiki/BBS
< (no title) | あげぷらDay >
perlで気分転換を見て血が騒いだので反応(笑
if(not 条件式){...} ってのでもアリ。つことで「Perlっぽく」書き直してみた例を以下に。ただし動かしてないので動作は保証しません(ぉ
#!/usr/local/bin/perl
sub usage{
print "usage:\n";
print "\t\n$0 テーブルファイル HTMLディレクトリ";
exit;
}
usage() if (@ARGV != 2);
$table_name = $ARGV[0];
$dir_name = $ARGV[1];
open(TABLE, $table_name) or die "Can't open table file '$table_name'";
# テーブルファイルを連想配列に格納
while (<TABLE>){
chomp();
my($old,$new) = split(/\t/, $_);
$table{$old} = $new;
}
close(TABLE);
#パターンマッチ一発で置換するための小細工
$pattern = join("|",sort {length($b) <=> length($a)} keys %table);
# ディレクトリ内のファイルを列挙
opendir(DIR, "$dir_name") or die "Can't open target dir '$dir_name'";
while ($html = readdir(DIR)) {
next unless($html =~ /\.htm/); # ファイル名に".htm"を含むファイルだけ処理
print "$html を処理中...";
my $text;
# 読み込む
unles(open(ORIGINAL, $html)){
print "読み込めませんでした。スキップします。\n";
next;
}
while (<ORIGINAL>) {
# テーブルに基づき、文字列置換
s/($pattern)/$table{$1}/og; #$patternは不変なのでoオプションを付けて高速化
$text .= $_;
}
close(ORIGINAL);
# HTMLを書き出す
unless(open(RESULT, "> $html")){
print "書き込めませんでした。スキップします。\n";
next;
}
print RESULT $text;
close(RESULT);
print "完了\n";
}
closedir(DIR);
exit;