Files can be opened for input or output using the open() function. As in languages like C, the open() statement associates a filehandle with a filename and a mode for the file, namely input, output or append.
Here are some examples. In these examples the function die exits after printing a diagnostic. It is separated by an or whose semantics is that the second part of the or is executed only if the first part fails.
open(INFILE, "input.txt") or die "Can't open input.txt"; # Open in read mode -- could also write open(INFILE,"<input.txt") open(OUTFILE, ">output.txt") or die "Can't open output.txt"; # > indicates open in (over)write mode open(LOGFILE, ">>my.log") or die "Can't open logfile"; # >> indicates open in append mode
Reading a file is achieved using the <> operator on a filehandle. In scalar context it reads a single line from the filehandle, while in list context it reads the whole file in, assigning each line to an element of the list:
$line = <INFILE>; # Read one line from INFILE into $line @lines = <INFILE>; # Read all lines from INFILE into list @lines
The <> operator is most often seen in a while loop:
while ($line = <INFILE>) { # assigns each line in turn to $line print "Just read in this line:", $line; }
The example above also introduces the print statement. The simplest form of the print statement takes a list of string arguments separated by commas. print can also take an optional first argument specifying which filehandle to print to:
print "Hello, world"; print "Hello ", $name,"\n"; print OUTFILE $record; print LOGFILE $logmessage;
To close a file, we call the function close with the corresponding filehandle.