Perl文件读写基础模式与参数解析
文件操作模式与参数说明: #mode operand create truncate #read < #write > yes yes #append >> yes
场景一:若文件打开失败则抛出异常 复制代码 代码如下: 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);
场景二:若文件打开失败则发出警告并继续执行 复制代码 代码如下: 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' $!"; }
场景三:将单个文件内容读取至数组 复制代码 代码如下: 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;
结束