首页 > 其他 > 详细

杰瑞学Perl之文件操作(1)

时间:2014-03-23 08:49:54      阅读:265      评论:0      收藏:0      [点我收藏+]

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之文件操作(1),布布扣,bubuko.com

杰瑞学Perl之文件操作(1)

原文:http://blog.csdn.net/jerry_1126/article/details/21830325

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!