Perl check if file handler is open

If you write a function in Perl and want to check if the file handler is already open you could use this function:

It returns 0 if its undefined,closed or not open, an 1 if the handler is open.

 

In this little example I open a file to read and another to write, I check the sub before and after the open function, and before and after the close function.

The Result, looks like expected:

Perl print __DATA__ multiple times

Sometimes you have a lot of Data in Perl and you want to store in your script, for that you could you the __DATA__ token, you could simple read it with a file handle:

If you use it more than one time you should seek for the start position:

Output looks like this:

Perl read/write File

This is a simple example how to write into a File with Perl, and then read from it.At first we write the numbers from 1 to 6 into the file, in the second we read from the file and print it on the screen, if you don’t want the “\n” at the end use the function chomp.

If you open a File for read use ‘<‘, for write ‘>’ and for append ‘>>’.

Result looks like:

you could check if a handler is open with this Perl handler function.