Perl学习笔记之文件操作
Perl对文件的操作,跟其它的语言类似,无非也就是打开,读与写的操作。
1.打开文件
#!c:/perl/bin/perl-w
useutf8;
usestrict;
usewarnings;
my$filename='test.txt';#或者用绝对路径,如:c:/perl/Learn/test.txt
if(open(MYFILE,$filename))#MYFILE是一个标志
{
printf"Canopenthisfile:%s!",$filename;
close(MYFILE);
}
else{
print"Can'topenthisfile!";
}
2.读取文件
#!c:/perl/bin/perl-w
useutf8;
usestrict;
usewarnings;
my$filename='test.txt';
if(open(MYFILE,$filename))
{
my@myfile=<MYFILE>;#如果要读取多行,用此方法,如果只读取一行为:$myfile=<>;
my$count=0;#要读取的行数,初始值为0
printf"Ihaveopenedthisfile:%s\n",$filename;
while($count<@myfile){#遍历
print("$myfile[$count]\n");#注意此种写法.
$count++;
}
close(MYFILE);
}
else{
print"Ican'topenthisfile!";
}
exit;
3.写入文件
#!c:/perl/bin/perl-w
useutf8;
usestrict;
usewarnings;
my$filename='test.txt';
if(open(MYFILE,">>".$filename))#此种写发,添加不删除
{#此种写法,重写文件内容MYFILE,">".$filename
printMYFILE"WriteFileappendingTest\n";
close(MYFILE);
}
else{
print"Ican'topenthisfile!";
}
exit;热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短