Perl:讀檔案
本文簡單說明perl 對檔案的開啟和寫資料到檔案的方法
假設有一個檔案名為abc.txt,而abc.txt 的內容如下
line 1
line 2
line 3
讀檔的範例如下:這樣可以把abc.txt從第一行讀到最後一行
open(open_file,"abc.txt") or "open file error" ;
while(<open_file>)
{
chomp ;
print "$_\n" ;
}
perl 對檔案的寫檔有二種方式,一種是建立新檔並寫入資料
範例如下
這樣abc.txt的內容就是:this is add data info,原本abc.txt的內容會被清掉,然後把$info的資料寫到檔案當中
open(write_file,">abc.txt") or "open file error" ;
my $info="this is add data info" ;
print write_file "$info" ;
而複寫資料到檔案的檔案如下
執行完上面的程式之後,再執行下面的程式,abc.txt的內容就會有二行相同的資料
open(append_file,">>abc.txt") or "open file error" ;
my $info="this is add data info" ;
print write_file "$info" ;
對檔案的處理,對於所建立的物件在不處理時,要有關掉的習慣
方法如下
close(object_name)
從上面的範例就是要close(write_file) 和close(append_file)
以上就是perl 處理檔案的方法
本文簡單說明perl 對檔案的開啟和寫資料到檔案的方法
假設有一個檔案名為abc.txt,而abc.txt 的內容如下
line 1
line 2
line 3
讀檔的範例如下:這樣可以把abc.txt從第一行讀到最後一行
open(open_file,"abc.txt") or "open file error" ;
while(<open_file>)
{
chomp ;
print "$_\n" ;
}
perl 對檔案的寫檔有二種方式,一種是建立新檔並寫入資料
範例如下
這樣abc.txt的內容就是:this is add data info,原本abc.txt的內容會被清掉,然後把$info的資料寫到檔案當中
open(write_file,">abc.txt") or "open file error" ;
my $info="this is add data info" ;
print write_file "$info" ;
而複寫資料到檔案的檔案如下
執行完上面的程式之後,再執行下面的程式,abc.txt的內容就會有二行相同的資料
open(append_file,">>abc.txt") or "open file error" ;
my $info="this is add data info" ;
print write_file "$info" ;
對檔案的處理,對於所建立的物件在不處理時,要有關掉的習慣
方法如下
close(object_name)
從上面的範例就是要close(write_file) 和close(append_file)
以上就是perl 處理檔案的方法
文章標籤
全站熱搜
