Presenting Mathematical Concepts on the World Wide Web
Forms & Scripts

Perl: 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
Back: Subroutines
Up: Forms & Scripts


Presenting Mathematical Concepts on the World Wide Web. Copyright © 1997 by Carol Scheftic. All rights reserved. (This section was originally copyrighted in 1996 by The Geometry Center and is re-used here with permission.) Please send comments on this page, or requests for permission to re-use material from this page, to: scheftic@geom.umn.edu
Page established 1-Jun-97; last updated Thursday, 24-Jul-1997 01:27:12 CDT.