天极Yesky
  • 笔记本电脑
    笔记本
  • 台式电脑
    台式机
  • 手机
    手机
  • 电脑硬件DIY
    DIY硬件
  • CPU
    主板
    音箱
  • 硬盘
    显卡
    键鼠
  • 内存光驱
    显示器
    机箱电源

  • 数码相机DC
    数码相机
  • MP3播放器
    MP3/MP4
  • 数码摄像机DV
    摄像机
  • 电脑外设
    外设
  • 网络
    网络
  • 服务器
    服务器
  • 数字家庭
    数字家庭
  • 群乐
    群乐
  • 产品报价 行情 经销商 渠道 评测 | 软件 设计 网页 开发 安全 论坛 E时代 游戏 图片 壁纸 下载 网摘 博客 索尼专区 Vista 科技奥运
    天极网
    Perl file maintenance
    作者: Tom Christiansen
    出处:
    责任编辑:
    [ 2004-06-17 19:08 ]


    Modifying a file in place without a temporary file

    From Perl Cookbook by Tom Christiansen and Nathan Torkington, O'Reilly and Associates, 1998.

    Problem

    You need to insert, delete, or change one or more lines in a file, and you don't want to (or can't) use a temporary file.

    Solution

    Open the file in update mode ("+<"), read the whole file into an array of lines, change the array, then rewrite the file and truncate it to its current seek pointer.

     
      open (FH, "+< FILE")    or die "Opening: $!"; 
      @ARRAY = ; 
      #  change ARRAY here 
      seek (FH, 0, 0)       or die "Seeking: $!"; 
      print FH @ARRAY    or die "Printing: $!"; 
      truncate (FH, tell (FH))   or die "Truncating: $!"; 
      close (FH)           or die "Closing: $!"; 
     

    The operating system treats files as unstructured streams of bytes. This makes it impossible to insert, modify, or change bits of the file in place. You can use a temporary file to hold the changed output, or you can read the entire file into memory, change it, and write it back out again.

    Reading everything into memory works for small files, but it doesn't scale well. Trying to on your 800 MB web server log files will either deplete your virtual memory or thrash your machine's VM system. For small files, though, it works:

     
      open (F, "+< $infile")            or die "can't read $infile: $!"; 
      $out = ''; 
      while () { 
       s/DATE/localtime/eg; 
       $out .= $_; 
      } 
      seek (F, 0, 0)             or die "can't seek to start of $infile: $!"; 
      print F $out              or die "can't print to $infile: $!";   
            truncate (F, tell (F))     or die "can't truncate $infile: $!"; 
      close (F)         or die "can't close $infile: $!"; 

    For more information on the book Perl Cookbook go to http://www.oreilly.com/catalog/cookbook/

    笔名:
    请您注意:

     遵守国家有关法律、法规,尊重网上道德,承担一切因您的行为而直接或间接引起的法律责任。

     天极网拥有管理笔名和留言的一切权利。
    相关内容