当前位置: 代码网 > it编程>网页制作>Perl > Perl学习笔记之文件操作

Perl学习笔记之文件操作

2024年05月15日 Perl 我要评论
perl对文件的操作,跟其它的语言类似,无非也就是打开,读与写的操作。1. 打开文件#! c:/perl/bin/perl -w use utf8; use strict; use warnings;

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; 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com