Perl comes with a number of built-in functions to read and
write files, retrieve file lists from directories, and obtain file and
directory properties. Reading a file is a very simple, three-step process in
Perl: Create a handle for the file with the open() function, read the file
contents from the file handle, and close the file with the close() function.
Here is an example of how this works:
# open file
open(FILE, "data.txt") or die("Unable to open file");
# read file into an array
@data = <FILE>;
# close file
Here, a file handle to “data.txt” is created with
the open() function; this file handle is named FILE.
The file handle is then used with Perl’s input operator <> to read the
contents of the file into the @data array. Each element of the array now
corresponds to one line of the file. Once the entire file has been read, the
handle is destroyed with the close() function.
If the file cannot be found, the open()
function generates an error, which can be trapped by die(), and script
processing is terminated.
To print the contents of the file, iterate over the array in
a loop and print each element. A foreach() loop is most suitable for this kind
of operation; add the following lines of code to the script above to have Perl
display the file’s contents after reading it:
# print file contents
foreach $line (@data)
Â Â Â Â Â print $line;
Important: For the script above to work, the user whom the
script is running as must have read privileges on the named file.
Download the Perl QuickStart to learn more
If you’re looking for more tips and tricks to help you
master Perl, download our free QuickStart: Perl PDF (free registration
required). There you’ll learn the basics to get started with this powerful