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+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 |
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