9.Perl の基礎9-3.ARGVの使用■ ファイルを開く その1
プログラム内でファイル名を指定しないでファイルを開く。
この場合、1つのファイルしか開けない。 郵便番号ファイル
#! /usr/bin/perl
@file = <>; # <>は実行時に指定したファイルを配列に代入。 foreach $line (@file) # $line にはファイルの1行分のデータが入いる。 { print "$line"; } exit;
$
$ ./file01.pl zip.txt 上のプログラムは次のようにも書けます。
#! /usr/bin/perl
foreach $line (<>) # $line にはファイルの1行分のデータが入いる。 { print "$line"; } exit; さらに・・・・
#! /usr/bin/perl
while (<>) { print "$_"; # $_ にはファイルの1行分のデータが入いっている。 } exit; ■ ファイルを開く その2
プログラム内でファイル名を指定してファイルを開く。
#! /usr/bin/perl
open(IN, "zip.txt"); @file = <IN>; close(IN); for($i=0; $i<@file; $i++) { print "$file[$i]"; } exit;
$
$ ./file02.pl # ファイルの指定が無いことに注意! ■ ファイルに書き込む その1
リダイレクトにより書き込む。
画面への出力をそのままファイルに書き込ませる。
#! /usr/bin/perl
open(IN, "zip.txt"); @file = <IN>; close(IN); for($i=0; $i<@file; $i++) { print "$i\t$file[$i]"; } exit;
$
$ ./file02.pl > test2.txt ■ ファイルに書き込む その2
プログラム内でファイル名を指定してファイルを開く。
#! /usr/bin/perl
open(IN, "test.txt"); @file = <IN>; close(IN); open(OUT, ">test2.txt"); # ファイルを開く。 for($i=0; $i<@file; $i++) { print OUT "$i\t$file[$i]"; } close(OUT); # ファイルを閉じる。 exit;
$
$ ./file03.pl |