Next: System Calls
Up: CGI Scripts with Perl
Prev: Subroutines

File I/O

Perl tries to interact smoothly with the operating system. The top layer of this interaction is file handling. This example opens a file. The variable IN is a filehandle

open(IN, ">test");

print IN "In we go";

close(IN);

Preceding the filename is a redirection character. By default, Perl reads data files one line at a time. There is a special syntax for reading the next line:

$filename = $ARGV[0];       #get command line argument

open(IN, "<$filename");

$line = <IN>;               #read the first line
print $line;

while(<IN>) {               #loop as long as not EOF
print $_;                   #loop variable -- contains current line
}
There are many short cut features in Perl. In particular, there are a host 'special variables' like $_.


Next: System Calls
Up: CGI Scripts with Perl
Prev: Subroutines

[HOME] The Geometry Center Home Page

Comments to: webmaster@geom.umn.edu
Created: May 08 1996 --- Last modified: Wed Jun 5 15:57:21 1996