Example eight - File I/O


# Example eight - File I/O.
# Reading from and writing to files is introduced, including
# OPEN, CLOSE and DIE.
#
# by Al Bento

# A first example of reading from a file.

open (READ,"example8.txt") || die "Could not open file\n";

print "This is the content of the read file\n\n";

while (<READ>) {chop; print" $_\n"; }
close (READ);

print "\n";

# a more interesting example of file I/O

$infile = "example8.txt";
$outfile = "example8a.txt";

open (READ, "<" . $infile) || die "Could not open file to read\n";
open (WRITE, ">" . $outfile) || die "could not open file to write\n";

print "This is the printout of the data written to the new file\n\n";

while (<READ>) {chop;
       ($name,$color) = split (/=/,$_);
       print WRITE "$name likes $color\n";
       print "$name likes $color\n";
}

close (READ);
close (WRITE);

download the script


This page is maintained by Al Bento who can be reached at abento@ubmail.ubalt.edu. This page was last updated on June 15, 1997. Although we will attempt to keep this information accurate, we can not guarantee the accuracy of the information provided.