Directory and File Handling #3

#0 | #1 | #2 | #3 | #4 | #5 | #6

Directories & Files

As mentioned, once we have a file opened and accessible, we are able to do several things with it.

But the first thing we need to know is how to close the file once we're finished working with it. We've already seen how this is done, but it's good to make sure you ALWAYS do this explicitly - don't count on Perl or the Operating System to do this for you:

close FILEHANDLE

Print to a file

In order to 'print' something to a file, we need to know whether we are going to be 'appending' data to it with several print statements, or just performing a single print, perhaps containing everything we want to print.

For example, any time you have print in a loop, it's probably a good bet that you want to open the file for 'appending' - >> .

open ($myFile,">>","newfile.txt")

Otherwise, we could likely use the regular > operator.

open ($myFile,">","newfile.txt")

You will have to use both, in different circumstances, for a while to see how each one works, and whether it does what you are expecting.

Of course, we remember to check the result of these operations, right?

open ($myFile,">>","newfile.txt") or die "Can't open $myFile: $!\n"

Here is where you create and write to a file! Add the following code to a new script and run it.

#! /usr/bin/perl
use strict;
use warnings;

BEGIN
{
	open (STDERR,">> $0.txt");
	print STDERR "\n", scalar localtime, "\n";
}

my $FirstFile = "myFirstFile.txt";
open my ($FILEHAND,">",$FirstFile) or die "Can't open $FirstFile: $!\n";
print ($FILEHAND "This should be the only line in this file.");
close $FILEHAND or die "Can't close $FirstFile: $!\n";

If you check the 'myFirstFile.txt' file, you will see that it contains just 1 line - we didn't add a newline to the end of our print statement.

You can delete that file, then run the script again, to see that it does work.

Next you can change a few things in that script. After the close $FILEHAND line add the following lines:

open my ($FILEHAND,">>",$FirstFile) or die "Can't open $FirstFile: $!\n";
print ($FILEHAND "\nNow I'm adding some new lines to it.\n");
close $FILEHAND or die "Can't close $FirstFile: $!\n";

I ran that script 3 times to end up with this:

This should be the only line in this file.
Now I'm adding some new lines to it.
This should be the only line in this file.
Now I'm adding some new lines to it.
This should be the only line in this file.
Now I'm adding some new lines to it.

Don't forget, we are 'printing' to the file twice with this script each time we run it.

But it is being 'created' new each time we run it, because in the first open statement we are using the > operator. This truncates the file, and then starts writing to it.

In the second print, we open the file with >> which appends our text to the end of it.

Next: Reading from a file