Perl provides various operations and functions to process files.
Perl File example
First, To process files for read or write, you have to open the files.
Syntax
open (filehandle,filemode,filepath)
filehandler: It is an cursor for a file, also called file stream or object.
file mode: contains three types
- Reading
<
- Write
>
- Append
>>
- Reading
FilePath:
Path to an file given, ie absolute or relative path
For example, Below line code to ope
n a file for reading,
open ( "handler" , '<' , 'test.txt' );
If any er`ror, use display an error with exit from a program execution.
open ( Read , '<' , 'test.txt' ) or die $!;
die $!: die used to exit the program $1
perl variable that displays the error stack message.
You can print the file, Finally close the file
close(handler)
how to Create a File in perl
This is an example of create an file and writes to a file.
open(my $filehandler, ">", "abc.txt") or die "Unable to open file: $!";
Open is an function that used for read and writing an file
First argument,$filehandler
is a variable created with my used to point the newly created a file.
Second Argument, >
indicates modes used for writing.
It does following things
- Create a file if does not exists
- if file already exists, it points to it. and overrides the content.
print function with filehandler variables,writes file content to opened file.
Finally, close the file
# Open the file for writing
open(my $filehandler, ">", "abc.txt") or die "Unable to open file: $!";
# Write to the file
print $filehandler "file content \n";
# Close the file
close $filehandler;
outputs, Create a abc.txt file and contains file content text
How to copy from one file to another file
open (READ, '<', 'test.txt') or die $!;
open (WRITE, '>', 'output.txt') or die $!;
# WHILe loop until End Of File
while(<READ>){
chomp $_;
print WRITE "$_\n";
}
close (READ);
close (WRITE);