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 a cursor for a file, also called a file stream or object.
file mode: contains three types
- Reading
<
- Write
>
- Append
>>
- Reading
FilePath:
Path to a file given, ie absolute or relative path
For example, Below line code to open a file for reading,
open ( "handler" , '<', 'test.txt' );
If any error, display an error with an 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 creating a file and writing to a file.
open(my $filehandler, ">", "abc.txt") or die "Unable to open file: $!";
Open is a function that is used for reading and writing a file
The first argument,$filehandler
is a variable created with my used to point the newly created file.
The second Argument, >
indicates modes used for writing.
It does the following things
- Create a file if does not exists
- if the file already exists, it points to it. and overrides the content.
print function with filehandler variables writes file content to the 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 an 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);