perl讀寫文件代碼實例
#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
相關(guān)文章
perl中的字符串操作函數(shù)chomp與chop介紹
這篇文章主要介紹了perl中的字符串操作函數(shù)chomp與chop介紹,chomp與chop都是用于去除字符串變量尾部的字符,但它們有各自的區(qū)別,需要的朋友可以參考下2015-02-02Windows和Linux系統(tǒng)下perl連接SQL Server數(shù)據(jù)庫的方法
這篇文章主要介紹了Windows和Linux系統(tǒng)下perl連接SQL Server數(shù)據(jù)庫的方法,本文詳細(xì)的講解了Windows和Linux系統(tǒng)中perl如何連接Microsoft SQL Server數(shù)據(jù)庫,需要的朋友可以參考下2014-10-10