zoukankan      html  css  js  c++  java
  • 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, "<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的简写。


  • 相关阅读:
    mysql查看进程
    mysql case, if
    centos升级python2.7
    centos多版本python安装pip
    Python library not found: libpython2.7mu.so.1.0
    pip cannot confirm SSL certificate: SSL module is not available
    python: no module named bz2
    summary
    python生成可执行文件保护源码
    mysql 存储过程
  • 原文地址:https://www.cnblogs.com/luhouxiang/p/2176316.html
Copyright © 2011-2022 走看看