1、讀取某檔案,如果該檔案不存在,則報錯,並提示出錯原因
open (DB, "/home/ellie/myfile") or die "Can't open file: $!\n";
運行後提示:Can't open file: No such file or director 2、讀寫檔案的方法:
open(FH, "<filename"); # Opens "filename" for reading.讀
# The <; symbol is optional.
open(FH, ">filename"); # Opens "filename" for writing.寫
# Creates or truncates file.
open(FH, ">>filename"); # Opens "filename" for appending.追加
# Creates or appends to file.
open(FH, "+<filename"); # Opens "filename" for read, then write.寫讀後寫
open(FH, "+>filename"); # Opens "filename" for write, then read.先寫後讀
close(FH);
3、開啟並列印該檔案
#!/usr/bin/perl
open(FH, "<d:/readtest.txt") or die "Can't open file: $!\n";
while(<FH>){ print }
4、檔案屬性
#!/usr/bin/perl
my $file="d:/readtest.txt";
# Is it readble, writeable, and executable?
print "File is readable, writeable, and executable\n" if -r $file and -w _ and -x _;
# When was it last modified?
print "File was last modified ",-M $file, " days ago.\n";
#若為目錄則列印
print "File is a directory.\n " if -d $file; # Is it a directory?
由於此檔案實際存在,並且是剛建不久,但只是普通的文字檔,因此最後的結果為File was last modified 0.0239930555555556 days ago. 若代碼:print "File is readable, writeable, and executable\n" if -r $file and -w _ and -x _;改為:print "File is readable, writeable, and executable\n" if -r $file and -w _ ;最後的結果則為:
File is readable, writeable, and executable
File was last modified 0.0251851851851852 days ago.
-w _為-w $file的簡寫。