Reading from, and writing to files

Back to the mundane but useful, reading to and writing from files.

To write to a file, you need to create a filehandle and then open the file. When you have finished writing, close the file.

There are 3 special file handles in Perl, STDIN the standard input, usually the keyboard, STDOUT the standard output, usually the screen, and STDERR the standard error device, again usually the screen.

The select command is useful when having multiple output sources

Here's an example Perl script to write to a file, and then to append to it.

#!/usr/local/bin/perl

open(MYOUTFILE,">output.txt"); ### open file for output
                               ### will detroy an old one if it exists.
print MYOUTFILE "Hello my new file!\n";
print MYOUTFILE "Hello again my new file!\n";

close MYOUTFILE;

print "Should be writing to the screen again.\n";

open (MYOUTFILE, ">>output.txt"); ### Open the output file again.
                                  ### but this time appending to it.

select  MYOUTFILE; ### Now a print without a file handle will 
                   ### default to MYOUTFILE;

print "This should go back again to my file\n";

print STDOUT "Even though the file is open this should go to the screen\n";

print "And we are back to the file again\n";

close MYOUTFILE;

select STDOUT;

print "And we are back to the screen again\n";

Here's how you read a file into your script:

#!/usr/local/bin/perl

### First open a file , hopefully with something in it.

open( MYINPUTFILE, ``input.txt'');

while (<MYINPUTFILE>){
print;
}

The angle brackets will take one line at a time, from the file pointed to by teh file handle within the brackets. Each line is read into the default scalar variable $_. The print command looks for this variable by default. Thus, this script simply prints out the file.


next up previous
Next: Saving state Up: Class 3 Stat 540 Previous: Random number generators

Richard Waterman
Fri Jan 29 06:45:16 EST 1999