zoukankan      html  css  js  c++  java
  • Perl文件读写

    Perl File Handling: open, read, write and close files

    #====================

    Opening files

    Solution 1:

    Opening a file in perl

    open FILE, "filename.txt" or die $!; # read

    open FILEHANDLE, MODE, EXPR

    The available modes are the following:

    modeoperandcreatetruncate
    read <    
    write >
    append >>  

    Each of the above modes can also be prefixed with the + character to allow for simultaneous reading and writing.

    modeoperandcreatetruncate
    read/write +<    
    read/write +>
    read/append +>>  

    open FILE, ">", "filename.txt" or die $!    #write

    open FILE, ">filename.txt" or die $!;   #write

    Solution 2:

    #!/usr/bin/perl
    
    open(FILE, "<file.txt") or die "Couldn't open file file.txt, $!";
    
    while(<FILE>){
       print "$_";
    }

    Following is the table which gives possible values of different modes

    EntitiesDefinition
    < or r Read Only Access
    > or w Creates, Writes, and Truncates
    >> or a Writes, Appends, and Creates
    +< or r+ Reads and Writes
    +> or w+ Reads, Writes, Creates, and Truncates
    +>> or a+ Reads, Writes, Appends, and Creates

    Solution 3:

    sysopen(FILE, "file.txt", O_RDWR|O_TRUNC );

    Following is the table which gives possible values of MODE

    EntitiesDefinition
    O_RDWR Read and Write
    O_RDONLY Read Only
    O_WRONLY Write Only
    O_CREAT Create the file
    O_APPEND Append the file
    O_TRUNC Truncate the file
    O_EXCL Stops if file already exists
    O_NONBLOCK Non-Blocking usability

     

    #====================

     

    Reading files

    read a text file line-by-line

    my @lines = <FILE>;

    while (<FILE>) { print $_; }

    while (my $line = <FILE>) { ...}

    read a file only a few characters at a time

    open FILE, "picture.jpg" or die $!; # read

    binmode FILE;

    my ($buf, $data, $n);

    while (($n = read FILE, $data, 4) != 0)

    { print "$n bytes read "; $buf .= $data; }

    close(FILE);

    #====================

    Writing files

    open FILE, ">file.txt" or die $!; #write

    print FILE $str;

    close FILE;

    #====================

    Closing files

    open FILE1, "file.txt" or die $!; # read

    open FILE2, "picture.jpg" or die $!; # read

    ...

    close FILE2;

    close FILE1;

     #====================

    REF:

    http://www.perlfect.com/articles/perlfile.shtml

  • 相关阅读:
    jstl表达式判断字符or字符串相等的写法
    enctype="multipart/form-data导致request获取不到数据
    Mac下解决mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
    单源文件目录makefile
    默认生成的特殊函数
    为什么说switch比if快
    C++基本内置类型
    补码的原理及其应用
    CSS--浮动与定位
    CSS--字体
  • 原文地址:https://www.cnblogs.com/emanlee/p/3843925.html
Copyright © 2011-2022 走看看