Perl学习笔记之文件操作
更新时间:2015年06月15日 09:40:49 投稿:junjie
这篇文章主要介绍了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;
相关文章
perl pop push shift unshift实例介绍
perl的pop跟push操作数组的最右边,shift跟unshift操作数组的最左边2013-02-02
Perl 和 StrawberryPerl 与 ActivePerl 的区别详解
这篇文章主要介绍了Perl 和 StrawberryPerl 与 ActivePerl 的区别详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-12-12


最新评论