Lesson 6

 




練習問題A


1. コマンドラインから処理するファイルを指定できるようにmerge.plを書き換えなさい。(merge.pllesson4で扱ったスクリプト。)

 

$fileA = $ARGV[0];
$fileB =
$ARGV[1];

open (INA, $fileA) or die;
open (INB, $fileB) or die;

while ($textA = <INA> and $textB = <INB>) {
   if ($textA eq $textB) {
      $textA =~ s/^\*/\n\*/;
      print $textA;
   } else {
      chomp $textA; print "$textA ($fileA)\n";
      chomp $textB; print "$textB ($fileB)\n";
   }
}

exit;

 

 


2.  下に示す txt2html.pl は,コマンドラインで指定した拡張子 .txt のファイルを全てHTML文書にするスクリプトである。スクリプトの内容を確認しなさい。

      txt2html.pl
      -----     -----

      #ファイル単位の処理をする
      undef $/;

    #コマンドラインで指定したファイルそれぞれに対して以下の処理を行う:
    foreach $infile (@ARGV) {

       #テキストファイル(*.txt)以外は処理しない
       next if ($infile !~ /\.txt$/);

       #出力ファイル名は入力ファイル名の拡張子部分を .html に変えたものにする
       $outfile =  $infile;
       $outfile =~ s/txt$/html/;

       #入力・出力ファイルを開く
       open (IN, $infile);
       open (OUT, ">$outfile");

       #ファイルの中身を読み込む
       $_ = <IN>;

       # < > をそれぞれ &lt; &gt; に置き換える
       s/</&lt;/g;
       s/>/&gt;/g;

       #前後にタグを付けて出力する
       print OUT  "<html>\n<body>\n<pre>\n";
       print OUT  $_;
       print OUT  "\n</pre>\n</body>\n</html>\n";

       #ファイルを閉じる
       close IN;
       close OUT;

    }

    exit;
    -----     -----