perl/条件分岐、ハッシュ、正規表現〜テキストファイルからhtmlを生成する〜
makehtml.plでmypage.txtをhtmlにしてみた。
makehtml.pl
#! usr/bin/perl use strict; use warnings; #変換ルールの設定 my %keyword = ( '----' => '<hr>', '-exit' => '<a href="http://www.yahoo.co.jp" target="_blank">yahoo</a>', '-home' => '<a href="http://www.google.co.jp" target="_blank">google</a>', '-notice' => 'リンクはご自由に。間違い等ありましたら、お気軽にご指摘ください。' ); if (@ARGV == 0){ print "Usage: perl makehtml.pl input.txt > output.html"; exit(-1); } print "<html>\n"; foreach my $file (@ARGV){ open(FILE, $file) or die "$!"; while (my $line = <FILE>){ chomp($line); if ($line =~ /^\*\*(.*)/){ print "<h2>$1</h2>\n"; }elsif ($line =~ /^\*(.*)/){ print "<center><h1>$1</h1></center>\n"; }elsif (exists($keyword{$line})){ print "$keyword{$line}\n"; }else{ print "$line\n"; } } close(FILE); } print "</html>\n";
mypage.txt
*welcome to my external memory unit pages ---- **hello nice to meet you. this pages are -home . ---- **introduction my name is komage. thank you for your visiting. please be friendly with me. ---- **the door to outsides i hope you to visit soon. see you soon! bye! -exit ---- -home ---- -notice
コマンドで以下のように打てば、htmlが生成されます。
makehtml.pl mypage.txt < 生成したhtmlファイルにつけたい名前