Read and write and delete a file in perl

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Read and write and delete a file in perl

In this article I’m going to try and show you some operation examples to read, write and delete a file in perl using a few methods, like the saying goes …

There’s more ways to skin a cat …

So yes, more ways to work on a file. It really depends the purpose for which you are reading this file. Perl is pretty much known to be one of the most used programming language for file operations. Even continuous looping and reading a file really easy, think tail -f filename in linux.

So lets get started.

How to read a file in Perl

To read a file you can pretty much use the basic file read handler operator. However, before using the read handler you need to open the file in all cases. To open the file you can use the open operator along with one of the following flag / operand:

mode operand create truncate
read <
write >
append >>

By default, if you do not specify the operand, it will be read as default. An example would like this:

Basically we try to open the file and, if possible,  save its content in our file handler MYFILE.

<MYFILE>  — The less and greater symbols (<,>) would indicate that you would want to split the content line by line into an array

Then we basically loop through the entire array and print each line at a time.

Another way which I found is to use the File::Slurp to read the entire file in one go into an array or directly into a scalar variable. I have used this a few times, however I still prefer the old / fashion way which is native to perl.

Anyway, an example:

Similar right? There are other ways too, but only properly use these two methods so far. For continuous reading a file, you could use the File::Tail module, use the following example:

This will read a file and print all new updates to it.

How to Write to a file in Perl

Again, similar way, just using the proper operand for appending / writing to the file:

What this will do is attempt to open the file data.txt if it exists, if not, this file will be created. Then print to your file handler the string in our scalar variable $str.

The way you do it in File::Slurp is again similar but this time using a different method for writing to your file:

What is good about this, is that you no longer need to loop the array and print the line to your file, File::Slurp will basically do this in one go.

How to Delete a file in Perl

This is rather simple, just need to use one simple command which, if I’m not wrong, is similar to most other languages. You would need to use the unlink method to delete the file. For example:

This would permanently remove the file from disk, so be careful when using this.

Request an article ←