Perl ファイルの入力出力
open関数を使ってファイルを開くことができる
open( ファイルハンドル, モード:文字コード, "ファイルパス" );
ファイルハンドル:読み込んだファイルの内容の名前
ファイルパス:読み込むファイルのパス
モード:openのモード 下記の表を参照
読み取り | 書き込み | 追加 | 新規作成 | 上書き | |
---|---|---|---|---|---|
< | ○ | × | × | × | × |
> | × | ○ | × | ○ | ○ |
>> | × | ○ | ○ | ○ | × |
+< | ○ | ○ | × | × | × |
+> | ○ | ○ | × | ○ | ○ |
+>> | ○ | ○ | ○ | ○ | × |
command | | command を実行し、その出力をパイプ経由でファイルハンドルを渡す | ||||
| command | 出力とファイルハンドルをパイプで command に渡す |
モードに何も付けなかった場合は、入力用(<)としてオープンされる。
> と >>の違いは、> はファイルを空にしてから上書きするのに対し、>> はファイルの終わりからデータを追加する。
+がつくと、ファイルを読み書き両用として利用可能(あまりオススメしないけど・・・)。
サンプル
-----------------
use strict;
use warnings;
use utf8;
binmode STDIN, ':encoding(cp932)';
binmode STDOUT, ':encoding(cp932)';
binmode STDERR, ':encoding(cp932)';
my $fpath1 = "intest.txt";
if(open(FH, "<:utf8", $fpath1) ){
print "Error:ファイル開けない\n";
exit 1;
}
my @data = <FH>;
close(FH);
foreach my $d (@data){
print $d;
}
my $fpath2 = "outtest.txt";
if(open(FH, ">:encodinf(cp932)", $fpath2) ){
print "Error:ファイル開けない\n";
exit 1;
}
print FH "昭和\n";
print FH "平成\n";
print FH "令和\n";
close(FH);
-----------------