Perl檔案讀寫

來源:互聯網
上載者:User

標籤:des   style   http   color   strong   檔案   

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:

mode operand create truncate
read <    
write > ? ?
append >> ?  

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

mode operand create truncate
read/write +<    
read/write +> ? ?
read/append +>> ?  

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

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

Solution 2:

#!/usr/bin/perlopen(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

Entities Definition
< 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

Entities Definition
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\n"; $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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.