Perlaccess : Tutorials : File and Directory
Opening Files (4.1)
by Jacob A. Wheeler
http://www.bigresources.com

This will most likely be one of your most widely used functions, open. Here you will learn the basics of opening and closing a file using perl. You will also learn to howto load the contents of a file into an array for output.

The following piece of code will open the file, file.txt for input. Saving the contents of the file to an array (@file)

  1. open (FILE, ">file.txt");
  2. @file = <FILE>;
  3. close(FILE);

Want to output the whole contents of a file? Checkout the below code that utilizes the while loop:

  1. open (FILE, "file.txt");
  2. while (FILE) { print; }
  3. close(FILE);

The following will do the same thing, however using a foreach loop, outputing line by line:

  1. open (FILE, "file.txt");
  2. foreach $a (FILE) { print $a; }
  3. close(FILE);