File handling


Here is the basic perl program which does the same as the UNIX cat command on a certain file.

 

#!/usr/local/bin/perl # # Program to open the password file, read it in, # print it, and close it again. $file = '/etc/passwd';		# Name the file open(INFO, $file);		# Open the file @lines = <INFO>;		# Read it into an array close(INFO);			# Close the file print @lines;			# Print the array

 

The open function opens a file for input (i.e. for reading). The first parameter is the filehandle which allows Perl to refer to the file in future. The second parameter is an expression denoting the filename. If the filename was given in quotes then it is taken literally without shell expansion. So the expression '~/notes/todolist' will not be interpreted successfully. If you want to force shell expansion then use angled brackets: that is, use <~/notes/todolist> instead.

The close function tells Perl to finish with that file.

There are a few useful points to add to this discussion on filehandling. First, the open statement can also specify a file for output and for appending as well as for input. To do this, prefix the filename with a > for output and a >> for appending:

 

open(INFO, $file);	# Open for input open(INFO, ">$file");	# Open for output open(INFO, ">>$file");	# Open for appending open(INFO, "<$file");	# Also open for input

 

Second, if you want to print something to a file you've already opened for output then you can use the print statement with an extra parameter. To print a string to the file with the INFO filehandle use

 

print INFO "This line goes to the file.\n";

 

Third, you can use the following to open the standard input (usually the keyboard) and standard output (usually the screen) respectively:

 

open(INFO, '-');	# Open standard input open(INFO, '>-');	# Open standard output

 

In the above program the information is read from a file. The file is the INFO file and to read from it Perl uses angled brackets. So the statement

 

@lines = <INFO>;

 

reads the file denoted by the filehandle into the array @lines. Note that the <INFO> expression reads in the file entirely in one go. This because the reading takes place in the context of an array variable. If @lines is replaced by the scalar $lines then only the next one line would be read in. In either case each line is stored complete with its newline character at the end.


Exercise

Modify the above program so that the entire file is printed with a # symbol at the beginning of each line. You should only have to add one line and modify another. Use the $" variable. Unexpected things can happen with files, so you may find it helpful to use the -w option as mentioned in the section on running Perl programs.