一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

perl读写文件代码实例实用指南

时间:2026-09-03 14:30:01 编辑:袖梨 来源:一聚教程网

平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“perl读写文件代码实例”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。

#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

热门栏目