bsbforever 发表于 2015-12-29 08:19:16

perl学习(2)文件处理

  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, &quot;<filename&quot;);   # Opens &quot;filename&quot; for reading.读
                           # The <; symbol is optional.
  

open(FH, &quot;>filename&quot;);   # Opens &quot;filename&quot; for writing.写
                           # Creates or truncates file.
  

open(FH, &quot;>>filename&quot;);   # Opens &quot;filename&quot; for appending.追加
                            # Creates or appends to file.
  
open(FH, &quot;+<filename&quot;);   # Opens &quot;filename&quot; for read, then write.写读后写
open(FH, &quot;+>filename&quot;);   # Opens &quot;filename&quot; for write, then read.先写后读
  
close(FH);               




3、打开并打印该文件


#!/usr/bin/perl
open(FH, &quot;<d:/readtest.txt&quot;) or die &quot;Can't open file: $!\n&quot;;
while(<FH>){ print }

4、文件属性




  #!/usr/bin/perl
  

my $file=&quot;d:/readtest.txt&quot;;
  

# Is it readble, writeable, and executable?
print &quot;File is readable, writeable, and executable\n&quot; if -r $file and -w _ and -x _;
  

# When was it last modified?
print &quot;File was last modified &quot;,-M $file, &quot; days ago.\n&quot;;
  

#若为目录则打印
print &quot;File is a directory.\n &quot; if -d $file; # Is it a directory?



由于此文件实际存在,并且是刚建不久,但只是普通的文本文件,因此最后的结果为

File was last modified 0.0239930555555556 days ago.      



若代码:print &quot;File is readable, writeable, and executable\n&quot; if -r $file and -w _ and -x _;



改为:print &quot;File is readable, writeable, and executable\n&quot; if -r $file and -w _ ;

最后的结果则为:  File is readable, writeable, and executable
File was last modified 0.0251851851851852 days ago.
  
  -w _为-w $file的简写。
页: [1]
查看完整版本: perl学习(2)文件处理