您的位置:寻梦网首页编程乐园CGI编程Zhanshou's CGI Tutorial

File I/O


In Perl, data can be read from the standard input file, STDIN, and written to the standard output file, STDOUT, or the standard error file, STDERR. For example, the following statement :

$inputline=<STDIN>
reads a line of content from the standard input file and :
print(STDOUT,"This is the content to write");
writes a string to the standard output file.

To access a common file other than STDIN, STDOUT, and STDERR:

  • First you must open the file using the built-in function open:
      open(MYFILE,"/home/pub/myfile");
    
    Here the first argument MYFILE is the file variable and the second argument is the file path name. By default, Perl assumes that you want to read the file that you open. To open a file for writing, put a >(greater) character in front of the file name :
      open(MYFILE,">/home/pub/myfile");
    
    When you open a file for writing, the original file will be destroyed. If you want to append to an existing file, put two > characters in front of the filename:
      open(MYFILE,">>/home/pub/myfile");
    
  • Then you can perform read or write to the file the same way as to STDIN and STDOUT:
    $inputline=<MYFILE>
    
    reads a line of content from input file and :
    print(MYFILE2,"This is the content to write");
    
    writes a string to the output file.

  • When you finish reading from or writing to a file, you can tell the system to close the file:
    close(MYFILE);
    
    Note that close() is not required: Perl automatically closes the file when the program terminates.

Previous Page Table of Content Next Page