Perl学习笔记之文件操作

发布时间:2022-04-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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学习笔记之文件操作全部内容,希望文章能够帮你解决Perl学习笔记之文件操作所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:PerlPerl