perl读写文件代码实例(perl读取文件最后一行)太疯狂了

随心笔谈9个月前发布 admin
203 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

本文讨论了在处理文件无法打开时的三种常见错误处理方式,结合代码示例进行说明。主要分为以下三种情况: 1. **直接抛出错误并关闭文件**:如果无法打开文件,程序会直接抛出错误并关闭文件,这种处理方式能够在第一时间终止程序运行,适用于对程序稳定性要求较高的情景。 2. **发出警告并继续运行**:如果无法打开文件,程序会发出警告但继续执行后续操作,这种方式能够帮助开发者排查问题,同时不影响程序的整体运行。 3. **读取文件内容到数组**:通过将文件内容读取到数组中,程序能够在无法完全打开文件时,至少能够处理部分数据。如果仍然无法打开文件,程序会抛出错误并关闭文件。 通过这三种方式的对比,可以帮助开发者根据具体需求选择合适的错误处理策略。



#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 “$row\n”;

}

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 “$row\n”;

}

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=;

for my $l (@FileContents){

print “$l\n”;

}

close FILEIN;

  

end

© 版权声明

相关文章