perl學習(2)檔案處理

來源:互聯網
上載者:User

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的簡寫。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.