|
||||
|
|
Perl File Input/Output
File Handling BasicsPerl was originally designed with a primary goal of efficiently processing textual data; reading and writing text files is quite straightforward. Consider a file named "presidents.txt" that contains the following information: George Washington Thomas Jefferson Alexander Hamilton Abraham Lincoln To read this file into an array and print out its contents on the screen, we could use something like this:
#!/usr/bin/perl -w
use strict;
my @file_contents;
open (FILEHANDLE, "<presidents.txt");
@file_contents = <FILEHANDLE>;
close FILEHANDLE;
foreach (@file_contents)
{
print $_;
}
pparadis@ubuntu-devel:~$ ./example.pl George Washington Thomas Jefferson Alexander Hamilton Abraham Lincoln We declare an array to hold the contents of the file, open a file handle named "FILEHANDLE" on the file, read the contents into the array, and close the file handle. We use a foreach loop to print the contents of the array on the screen. Each line in the text file is stored in a separate array index. In our open statement, notice the less-than sign that precedes the filename; this lets Perl know we're opening the file for input. What if we wanted to read the file, change all the names to uppercase characters, and write it back to disk? We'd make some changes to our program, as shown below:
#!/usr/bin/perl -w
use strict;
my @file_contents;
open (FILEHANDLE, "<presidents.txt");
@file_contents = <FILEHANDLE>;
close FILEHANDLE;
open (FILEHANDLE, ">presidents.txt");
foreach (@file_contents)
{
print FILEHANDLE uc($_);
print uc($_);
}
close FILEHANDLE;
pparadis@ubuntu-devel:~$ ./example.pl GEORGE WASHINGTON THOMAS JEFFERSON ALEXANDER HAMILTON ABRAHAM LINCOLN After reading in the file's contents, we re-open the file for output using the greater-than operator before the filename. This tells Perl to overwrite anything that was previously contained in the file, or create it if it doesn't already exist. Inside our foreach loop, we've added a new print statement which directs its output to FILEHANDLE instead of the screen. As each line is sent to the output file, it's first converted to uppercase via the uc function. As a visual aid, we send the same text to the screen. The next chapter introduces subroutines and code reuse, allowing you to write blocks of code that you can drop into new programs to perform common tasks. Continue: Subroutines and Code Reuse Table of Contents
|
|||
| All contents Copyright © 2007-2011 ClassHelper.org®. Please see our Privacy Policy. | ||||