トークンごとに処理する

まずは、練習として、英数字からなる文字列を予約語として扱ってみる。

SourceToHtml5.plx


# ヘッダ部
fileCopy(".\\Template\\header.txt");

# ソース部の変換
putLine($line) while ($line = getLine());

# フッタ部
fileCopy(".\\Template\\footer.txt");

# ファイルのコピー
sub fileCopy
{
my ($fileName) = @_;

open(F, $fileName) || die "open: $!";
print while (<F>);
close(F);
}

# 1行ずつ読み込む
sub getLine
{
# 1行読み込む
$_ = <>;

# TABを空白に変換
while(($pos = index($_, "\t")) >= 0) #TABがあるか
{
$num = 4 - ($pos % 4); #空白何文字分に置き換えればよいか
$_ = substr($_,0,$pos).(' ' x $num).substr($_,$pos+1); #空白に置き換え
}

# 行末の空白を削除
s/ +$//;

# 変換結果を返す
return $_;
}

# 1行ずつ書き込む
sub putLine
{
my($line) = @_;
my $token = "";

# 改行コードを取り除く
chomp($line);

while(length($line))
{
if ($line =~ /./)
{
# 1文字取得
$_ = $&;

# 1文字切り詰める
$line = substr($line, length($_));

# 英数字なら、トークンに追加
if (/[A-Za-z0-9_]/)
{
$token .= $&;
}
else
{
# 未出力のトークンを書く
if (length($token))
{
print "<SPAN CLASS=\"KEY\">".$token."</SPAN>";
$token = "";
}

# <, >, &, |, (, ) を置換
s/&/&#x26;/g; # &
s/</&#x3C;/g; # <
s/>/&#x3E;/g; # >
s/\(/&#x28;/g; # ( はてな
s/\)/&#x29;/g; # ) はてな
s/\|/&#x7C;/g; # | はてな

print $_;
}
}
}

# 未出力のトークンを書く
if (length($token))
{
print "<SPAN CLASS=\"KEY\">".$token."</SPAN>";
$token = "";
}

# 改行
print "\n";
}

実行形式


C:\Perl5>jperl SourceToHtml5.plx input.txt > output.txt