perl读写文件代码实例
程序员文章站
2024-01-03 13:59:10
#mode operand create truncate
#read <
#write > yes yes&n...
#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 = <filein>;
for my $l (@filecontents){
print "$l\n";
}
close filein;
end