Perl Operators   «Prev 

Opening a file in Perl

You can open a file with one of these forms of the open function:
# opens file $filename for input
open(HANDLE, "<$filename");

# opens file $filename for
# output (replaces file)
open(HANDLE, ">$filename");

# opens file $filename for
# output (appends to file)
open(HANDLE, ">>$filename"); 

# opens file $filename for input
# and output (file must exist)
open(HANDLE, "+<$filename"); 

# opens file $filename for input 
# and output (replaces file)
open(HANDLE, "+>$filename"); 

When you are done with the file, the close function:
close HANDLE
is used to free up the resources that are used by having the file open.

File Description in Perl

A file is a series of bytes stored on a disk instead of inside the computer's memory. A file is good for long-term storage of information. Information in the computer's memory is lost when the computer is turned off. Information on a disk, however, is persistent. It will be there when the computer is turned back on. We already know how to create a file using a text editor program. In this chapter, you'll see how to manipulate files with Perl. There are four basic operations that you can do with files. You can open them, read from them, write to them, and close them. Opening a file creates a connection between your program and the location on the disk where the file is stored. Closing a file shuts down that connection.
Every file has a unique fully qualified name so that it can't be confused with other files. The fully qualified name includes the name of the disk, the directory, and the file name. Files in different directories can have the same name because the operating system considers the directory name to be a part of the file name. Here are some fully qualified file names:
c:/windows/command/scandisk.ini
c:/a_long_directory_name/a_long_subdirectory_name/a_long_file_name.doc

Caution: You may be curious to know if spaces can be used inside file names. Yes, they can. But, if you use spaces, you need to surround the file name with quotes when referring to it from a DOS or UNIX command line. Note It is very important that you check for errors when dealing with files. To simplify the examples in this module, little error checking will be used in the example.