perl读写文件代码实例

所属分类: 脚本专栏 / perl 阅读数: 606
收藏 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胶水实现前后台对接的方法

Perl胶水实现前后台对接的方法,有需要的朋友可以参考下
收藏 0 赞 0 分享

Perl localtime时间函数的应用介绍

Perl时间函数localtime的使用介绍,这里简单的介绍下,更多请查看官方介绍
收藏 0 赞 0 分享

让apache2以cgi方式运行perl cgi程序的实现方法

让apache2以cgi方式运行perl cgi程序的方法,供大家学习参考
收藏 0 赞 0 分享

perl处理xml的模块介绍

perl处理xml的模块介绍,需要的朋友可以参考下
收藏 0 赞 0 分享

Perl从文件中读取字符串的两种实现方法

有时候我们需要从文件中读取字符串,这里简单介绍下, 需要的朋友可以参考下
收藏 0 赞 0 分享

perl 标量和运算符的一些知识介绍

有关perl的标量和运算符的一些知识,有需要的朋友可以看看
收藏 0 赞 0 分享

perl控制流介绍(if条件,while,for循环,foreach)

Perl控制流(if条件,while,for循环),需要的朋友可以参考下
收藏 0 赞 0 分享

Perl文件读取的经典用法分享

Perl文件读取的经典用法,有需要的朋友可以参考下
收藏 0 赞 0 分享

perl大文件读取处理的模块介绍

perl CPAN中有一个Tie-File 模块极大方便了对大文件的操作
收藏 0 赞 0 分享

perl跳过首行读取文件的实现代码

要求直接跳过第一行,然后读取后面的内容,以下代码来自网络,感谢原作者的辛苦劳动,顺祝新年快乐
收藏 0 赞 0 分享
查看更多