欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

相关标签: perl 读写文件

上一篇:

下一篇: