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的简写。


  • 相关阅读:
    偏最小二乘法回归(Partial Least Squares Regression)
    今天就来聊聊产品运营
    VS2005终于不“变态”了!
    Android 里的对话框Dialog 实现机制基础
    C#多线程操作界面控件的解决方案
    转C++ ,C#数据类型对照
    关于Linq to sql 应用时出现的一个‘row not found or changed’ 异常
    Android之Context Memu
    HttpModule的认识
    Docker:官网文档 Get Started 笔记
  • 原文地址:https://www.cnblogs.com/luhouxiang/p/2176316.html
Copyright © 2011-2022 走看看