TWクラブ【BloodyRosary】@8.ファイル操作


open関数	ファイルを開く

	open(IN,"log.txt");		log.txtという記録ファイルを、INというファイルハンドルで読み込む。
	@file = ;				読み込んだ記録ファイルを配列@fileにセットする。
	close(IN);  			読み込み処理を閉じる。

	print "@file[0]";			読み込んだファイルの1行目を表示する。


・ファイルの読み書き

	読み込みモードでオープン		open (FH, "file")
					open (FH, "< file")  
	上書きモードでオープン		open (FH, "> file") 
	追加書き込みモードでオープン	open (FH, ">> file") 
	読み書き両用モードでオープン	open (FH, "+> file")
	  				open (FH, "+< file")
	パイプ出力用でオープン		open (FH, "| コマンド") 
	パイプ入力用でオープン		open (FH, "コマンド |") 


・ファイルの上書き

	例

	open(OUT,"> log.txt");
	print OUT "DEF";
	close(OUT); 
			log.txtに「DEF」という文字列を上書き(中身を消して新たに書き込むことになる)
			追加書き込みしたい場合は >> を使う


・コマンドからパイプ入力用にオープン

	例

	open(IN,"ls -l |");
	@cmd = ;
	close(IN);

	foreach $cmd (@cmd) {
		print "$cmd \n";
	} 
			ls -l (カレントディレクトリ内のファイル名を取得) というコマンド
			を実行し、その結果を配列@cmdに格納し、表示する。 


・or die

	例

	open (FILE, "data001.txt") or die "Failed to open a file\n";

	ファイルオープンに失敗したら、Failed to open a file と
	標準エラー出力に出力し、プログラムを終了する

	if文で表現する場合は

	if (! open (FILE, "data001.txt") ) {
	    die "Failed to open a file\n";
	}

	と書く

Perl目次に戻る

別館TOPに戻る
ブログに戻る

BloodyRosary
Presents by 【BloodyRosary】
Copyrights (C) NEXON Corporation and NEXON Co., Ltd.
All Rights Reserved.