Perl學(xué)習(xí)筆記之文件操作
更新時(shí)間:2015年06月15日 09:40:49 投稿:junjie
這篇文章主要介紹了Perl學(xué)習(xí)筆記之文件操作,本文分別給出了打開文件、讀取文件、寫入文件代碼實(shí)例,需要的朋友可以參考下
Perl對文件的操作,跟其它的語言類似,無非也就是打開,讀與寫的操作。
1. 打開文件
#! c:/perl/bin/perl -w use utf8; use strict; use warnings; my $filename = 'test.txt'; # 或者用絕對路徑,如: c:/perl/Learn/test.txt if(open(MYFILE,$filename)) # MYFILE是一個(gè)標(biāo)志 { printf "Can open this file:%s!", $filename; close(MYFILE); } else{ print "Can't open this file!"; }
2. 讀取文件
#! c:/perl/bin/perl -w use utf8; use strict; use warnings; my $filename = 'test.txt'; if(open(MYFILE,$filename)) { my @myfile = <MYFILE>; #如果要讀取多行,用此方法,如果只讀取一行為:$myfile = <>; my $count = 0; #要讀取的行數(shù),初始值為0 printf "I have opened this file: %s\n", $filename; while($count < @myfile){ #遍歷 print ("$myfile[$count]\n"); #注意此種寫法. $count++; } close(MYFILE); } else{ print "I can't open this file!"; } exit;
3. 寫入文件
#! c:/perl/bin/perl -w use utf8; use strict; use warnings; my $filename = 'test.txt'; if(open(MYFILE,">>".$filename)) #此種寫發(fā),添加不刪除 { #此種寫法,重寫文件內(nèi)容 MYFILE,">".$filename print MYFILE "Write File appending Test\n"; close(MYFILE); } else{ print "I can't open this file!"; } exit;
相關(guān)文章
perl 指定長度并生成一個(gè)隨機(jī)的DNA序列的腳本代碼
perl 指定長度并生成一個(gè)隨機(jī)的DNA序列的代碼,有需要的朋友可以參考下2013-03-03perl數(shù)據(jù)庫添加、刪除、更新、查詢操作例子
這篇文章主要介紹了perl數(shù)據(jù)庫添加、刪除、更新、查詢操作例子,本文直接給出操作代碼,需要的朋友可以參考下2014-08-08perl用grep map求交集、并集、補(bǔ)集的實(shí)例代碼
perl 用grep map求交集、并集、補(bǔ)集的例子,有需要的朋友可以參考下2013-02-02