zoukankan      html  css  js  c++  java
  • 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输出到文件。

  • 相关阅读:
    地图初步
    多线程技术 初步
    核心动画 CAAnimation 进阶
    CALayer 进阶
    Quartz 2D 初步
    UIView 面面观
    CABasicAnimation 基础
    CGAffineTransform 放射变换解析 即矩阵变换
    RunTime 入门
    对Viewcontroller在UINavigationController中入栈出栈的一点点理解
  • 原文地址:https://www.cnblogs.com/hanleilei/p/2389725.html
Copyright © 2011-2022 走看看