File management
homencsa resources partnershipsoutreachsoftware_tech
alliance searchinside ncsa adv_computingsciencedivisions
left up right comment

File management

Perl has very robust mechanisms for dealing with file input/output. The operators are similar to the forms of redirection you use on the command line, including > < >> | etc. The syntax is
 
	open(FILEHANDLE,FILENAME); 
	close(FILEHANDLE); 
Conventions for opening files
"FILE" open FILE for input also "<FILE"
"> FILE" open FILE for output, creating if necessary
">> FILE" open FILE for appending
"+> FILE" open FILE with read/write access
"| CMD" open a pipe to CMD
"CMD |" open a pipe from CMD
Note the CMD can be an arbitrary bourne shell command, including its own pipes, redirection, etc.

Now that we have a filehandle, we need to read or write to it. The read operator is < >, as in

 
	# in a scalar context, read one line 
	$line = <FILEHANDLE>; 
	# in an array context, read the entire file (careful - this can take 
	#   lots of memory!) 
	@lines = <FILEHANDLE>; 
To print to a FILEHANDLE, print takes an optional first argument which is the filehandle. How does it distinguish the first argument from the list of scalars to print? (warning - loss of beauty ahead) print takes a list as an argument (which as you'll remember is denoted by commas), so the first argument does not have a comma.
 
	print(FILEHANDLE "your","list","here"); 

Example

 
	# get ready to send the mail 
	if ( ! open(MAIL,"| $sendmail $recipient") ) { 
	    &error("Could not start mail program"); 
	} 

left up right comment



NCSA
The National Center for Supercomputing Applications

University of Illinois at Urbana-Champaign

johnsonb@ncsa.uiuc.edu

Last modified: June 19, 1997



Retrieved by Memoweb from http://www.ncsa.uiuc.edu/General/Training/PerlIntro/files.html at 08/02/99