perl读写文件代码实例

所属分类: 脚本专栏 / perl 阅读数: 477
收藏 0 赞 0 分享

#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 指定长度并生成一个随机的DNA序列的脚本代码

perl 指定长度并生成一个随机的DNA序列的代码,有需要的朋友可以参考下
收藏 0 赞 0 分享

perl生成特定碱基比例的随机序列的代码

怎么用perl程序,随机生成一条序列,使ACGT四种碱基的含量分别为0.3,0.3,0.2,0.2!
收藏 0 赞 0 分享

学习perl的unless控制结构

在perl的if控制结构中,只有当条件表达式为真时才执行某块代码。如果想让程序块在条件为假时才执行,此时可以把if改成unless
收藏 0 赞 0 分享

有关perl正则表达式的一些杂项

有关perl正则表达式的一些杂项,有需要的朋友可以参考下
收藏 0 赞 0 分享

perl中heredoc使用说明

在成块打印文本的时候特别有用,需要的朋友可以参考下
收藏 0 赞 0 分享

Perl使用chdir的实例代码

Perl使用chdir的例子,供朋友们参考学习
收藏 0 赞 0 分享

perl特殊符号及默认的内部变量

perl特殊符号及默认的内部变量,有需要的朋友不妨参考下
收藏 0 赞 0 分享

perl中my与our的区别介绍

our 和 my 一样,都是对变量的声明,不过 our 声明的是包全局变量,而 my 声明的是词法变量
收藏 0 赞 0 分享

在vim中添加perl注释时无法对齐问题的解决方法

在使用vim编辑perl脚本时,每当输入#号时,#号都会跑到行首问题,需要的朋友可以参考下
收藏 0 赞 0 分享

perl 文件操作总结

perl 文件操作总结,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多