A5下载文章资讯

分类分类

perl读写文件代码实例

2015-05-08 14:29作者:zhao

#mode operand create truncate

#read <

#write > yes yes

#append >> yes

Case 1: Throw an exception if you cannot open the file:

use strict;

use warnings;

my $filename = 'data.txt';

open(my $fh, '<:encoding(UTF-8)', $filename)

or die "Could not open file '$filename' with the error $!";

while (my $row = <$fh>) {

chomp $row;

print "$rown";

}

close($fh);

Case 2: Give a warning if you cannot open the file, but keep running:

use strict;

use warnings;

my $filename = 'data.txt';

if (open(my $fh, '<:encoding(UTF-8)', $filename)) {

while (my $row = <$fh>) {

chomp $row;

print "$rown";

}

close($fh);

} else {

warn "Could not open file '$filename' $!";

}

Case 3: Read one file into array

use strict;

use warnings;

my $filename = 'data.txt';

open (FILEIN, "<", $filename)

or die "Could not open file '$filename' with the error $!";

my @FileContents = <FILEIN>;

for my $l (@FileContents){

print "$ln";

}

close FILEIN;

end

展开全部

相关

说两句网友评论
    我要跟贴
    取消