Perl学习笔记之文件操作
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是一个标志 { 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; #要读取的行数,初始值为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)) #此种写发,添加不删除 { #此种写法,重写文件内容 MYFILE,">".$filename print MYFILE "Write File appending Test\n"; close(MYFILE); } else{ print "I can't open this file!"; } exit;
相关推荐
边城客栈学无止境 2020-07-05
Walter的学习笔记 2020-07-04
A宇 2020-06-14
边城客栈学无止境 2020-06-10
邓博学习笔记 2020-06-03
davidliu00 2020-05-26
ShiShuo 2020-05-16
Aggressivesnail 2020-05-10
ShiShuo 2020-04-26
hanxingwang00 2020-04-22
davidliu00 2020-03-06
ShiShuo 2020-03-06
ShiShuo 2020-03-05
Aggressivesnail 2020-02-28
aaLiweipeng 2020-02-01
amberom 2020-01-16
Walter的学习笔记 2020-01-06