Directory and File Handling #4

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

Directories & Files

Reading from a file

Now that we can write to file, it makes sense we should also know how to read from one. Perl being Perl, there are several ways you can do this.

Let's try the first one - passing a filename to our script to read from. A new script is needed for this:

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

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

while (<>) {
    print;
}

Yes, that's all we need in there! You can see we have a loop, but inside the parentheses are 2 'angle brackets'.

Oddly enough, they are called Angle Operators or Line Input Operators.

We normally place a FILE HANDLE between the brackets.

During a while loop, IFF (IF AND ONLY IF) the brackets are the only things inside the conditional, the value is automatically assigned to $_ the special variable.

So in our case, if we put the name of a text file AFTER our script on the command-line, it will take that file name, and place it into $_.

Then 'while' there is anything in that file, it should print the contents of that file.

First we have to save that script as 'printIt.pl' in the same directory as all our previous ones. Make sure the directory contains a text file we can use to test it.

Using the file we created with our previous page, 'myFirstFile.txt' (if you still have it), enter this in your shell:

./printIt.pl myFirstFile.txt

You may have to run your Perl script differently than me, but however you do it, add the name of a text file after it and execute it.

Hopefully you should get something like this:

We can pass more than 1 file to it though: try entering a couple of text-file names to it.

Here, I've also added the name of the script itself.

./printIt.pl myFirstFile.txt printIt.pl

More ...