Perl 学习手札之十二:Files IO

understanding blocks and streams

there are two ways to look at files

 -blocks of data

 -stream

a block of data simply a chunk of the file that can be written or read in one operation.

 

a stream is data that may come as a series of bytes

 - keystrokes from a user

 - data sent over a network connection

 

handles.pl

# !/usr/bin/perl
#

use strict;
use warnings;

main( @ARGV);

sub main
{
     open(FH,  ' < '' workingfile.txt ') or error( " cannot open file for read($!) ");
     # print while <FH>;
     open(NFH,  ' > '' newfile.txt ') or error( " cannot open file for write($!) ");  
    
     print NFH  while <FH>;
      
     close FH;
     close NFH;
}

sub message
{
     my  $m =  shift or  return;
     print( " $m\n ");
}

sub error
{
     my  $e =  shift ||  ' unkown error ';
     print(STDERR  " $0: $e\n ");
     exit  0;
}

 


oofiles.pl

# !/usr/bin/perl
#

use strict;
use warnings;
use IO::File;

main( @ARGV);

sub main
{
     my  $fh = IO::File->new( ' workingfile.txt ', ' r ') or error( " can not open file for read($!) ");
     my  $nfh = IO::File->new( ' newfile.txt ', ' w ') or error( " can not open file for write($!) ");
     # print while <$fh>;
     while( my  $line =  $fh->getline){
         $nfh-> print( $line);
    }

}

sub message
{
     my  $m =  shift or  return;
     print( " $m\n ");
}

sub error
{
     my  $e =  shift ||  ' unkown error ';
     print(STDERR  " $0: $e\n ");
     exit  0;
}

 应用面向对象的方法操作。可以

 

binary.pl

# !/usr/bin/perl
#

use strict;
use warnings;
use IO::File;

main( @ARGV);

sub main
{
     my  $origfile =  " olives.jpg ";
     my  $newfile =  " copy.jpg ";
     my  $bufsize =  1024* 1024;
    
     my  $origfh = IO::File->new( $origfile, ' r ')
        or error( " cannot open $origfile($!) ");
     my  $newfh = IO::File->new( $newfile, ' w ')
        or error( " cannot open $newfile($!) ");
        
     $origfh-> binmode( " :raw ");
     $newfh-> binmode( " :raw ");
    
     my  $buf =  '';
     while( $origfh-> read( $buf, $bufsize)){
         $newfh-> print( $buf);
    }
    message( " done ");
}

sub message
{
     my  $m =  shift or  return;
     print( " $m\n ");
}

sub error
{
     my  $e =  shift ||  ' unkown error ';
     print(STDERR  " $0: $e\n ");
     exit  0;
}

 注意:用到的binary mode。我们是用面向对象的方法打开文件,读到buffer里面,然后print输出到文件。

 

 

 

 

 

posted on 2012-03-11 16:16 韩英武 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/hanleilei/archive/2012/03/11/2389725.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值