Perl Variables  «Prev 

Perl File Input Output

Simple file I/O

To open a file, you use the open() function like this:

open(HANDLE, ">filename");
  # open for write
open(HANDLE, ">>filename");
  # open for append
open(HANDLE, "<filename");
  # open for read

To write to the file, use print with the file handle:
print HANDLE
 "what to print goes here\n";

Do not use a comma after the file handle when printing to a file.
To read from a file, use one of these methods:

@array = <HANDLE>;
chomp @array; 
  # eats all the line endings



The first method reads the entire file into an array.
while(<HANDLE>) {
# chomp removes the line ending
 chomp;
# the $_ variable is
# the current line        
  print "$_\n"; 
}

The second method reads each line into the special $_ variable, and allows you to process each line separately.
To close the file, use the close function:
close(HANDLE);

For example, this program prints our Best Picture database to a file:

#!/usr/bin/perl -w
$filename = shift || "bestpix.txt";
@bestpix = ( 
"Ordinary People",
"Chariots of Fire", "Gandhi",
"Terms of Endearment", "Amadeus",
"Out of Africa", "Platoon",
"The Last Emperor", "Rain Man",
"Driving Miss Daisy",
"Dances with Wolves",
"The Silence of the Lambs",
"Unforgiven",
"Schindler's List", "Forrest Gump",
"Braveheart", "The English Patient",
"Titanic" );

open(OUTPUT, ">$filename")
 or die "can't open $filename: $!\n";
print "Writing to $filename\n";
print OUTPUT join("\n", @bestpix), "\n";
close(OUTPUT);
print "Done.\n";

This program reads it back in:
#!/usr/bin/perl -w
$filename = shift || "bestpix.txt";

open(INPUT, "< $filename")
 or  die "can't open $filename:  $! \n";
print "Reading from $filename ...\n";
@bestpix = <INPUT>;
# lose all the line endings
 chomp  @bestpix;
close(INPUT);
print join(', ', @bestpix), "\n";
A few quick notes about these programs:
  1. The line $filename = shift || "bestpix.txt" will assign a command-line parameter to $filename,
    or will use the default value if no command-line parameter is supplied.
  2. The die function is used to exit with an error message.
  3. The special variable $! contains the error message from the last operating-system error.
    It is useful for error messages like this.
  4. chomp will remove both CR and LF on DOS-based machines, or just the LF on Unix machines.
    Use this instead of the old chop wherever possible.