Perl-15-File Operations

Source: Internet
Author: User

Perl uses a variable called the file handle type to operate files; perl uses a file handle to establish an I/O channel between files in the program and external memory that can exchange data with external storage media. We recommend that all file handles be represented by uppercase letters, compared with common variables, Perl provides three built-in and special file handle variables: stdin, stdout, and stderr, which represent standard input, standard output, and standard error output respectively; 1. open and close the file: 1. open the file: open the file using the open () function in Perl. The syntax for opening the file is as follows: $ openflag = open (filehandle, "FILENAME"); filehandle: The city file handle, used to store a unique file identifier; filename: the name of the file to be opened, either relative or absolute; the open () function establishes a channel between the file handle filehandle and the file name filename for external data IO; the return of the open () function The return value is a value indicating true or false. It is used to determine whether the file is successfully opened. If the file is successfully opened, the true value (not null) is returned. If the file fails to be opened, returns a false value (null). There are three methods to determine the operation to open the file: A: If (open (filehandle, "FILENAME ")) {# operations when the file is successfully opened} else {# operations when the file fails to be opened} B: Unless (open (handle, "FILENAME ")) {# operation when opening a file fails;} C: open (filehandle, "FILENAME") | die ("can't the file: $! "); Die () function and built-in variable $! Used Together to print error information; 2. close the file: after using the file, close the file at any time to refresh the input/output buffer associated with the file handle; the syntax for closing a file is as follows: Close (filehandle); in fact, the operating system will save all output of the file handle in the system buffer until the file handle is closed or the File Buffer is filled up; this is an optimization method implemented by the operating system. 3. File Access Mode: Perl provides four access modes for file access: read, write, append, and read/write. Note the following: you cannot access a file in both read/write and append modes. The file access mode is specified by a special symbol appended to the file name. File Access Mode sample: Read mode example) open (FH, "<FILENAME"); read and write from the file (write) Open (FH, "> FILENAME"); write to the file, overwrite the content in the old file append open (FH, "> FILENAME"); append data to the end of the existing file to read and write (Read and write) Open (FH, "+ <FILENAME"); read and write existing file write program open (pipeout, "| pipeout "); open the program pipeline to read the program open (pipein, "pipein |"); get data from the program or command Output 2. File Name and file handle: open () the file name in the function can be a relative or absolute path. Each component of the file path can be parsed through the file: basename module in perl5, the functions in this module can parse the file name, path name, and extension that constitute the file location information. The file handle is a direct connection between the computer and the file. The file handle is used to read and write files. It is generated using the open () function. The file handle is also a variable type and uses standard variable naming rules, but does not start with $. Generally, all file handle variables are represented by uppercase letters to indicate the differences with other variables. When the perl5 program starts, it opens three default file handles: ◆ stdin: standard input, the default value is keyboard input. This file handle is used when the program inputs data from the command line. All input data from the command line is stored in the special built-in array variable @ argv of perl5; ◆ stdout: standard output, which is set to the computer's display by default. You can use the file handle and print function to send the program running results to the output device. ◆ stderr: Standard Error output, the default value is the computer's display. If the program wants to track errors, you can set stderr to output to the error file. stdin, stdout, and stderr can both be redirected to a file, or they can all be associated with a file so that the standard input is from the file, or the standard output content is output to the file, or the standard error information is output to the file for storage; 3. File Reading: There are two ways to read a file. One is to use computer memory to read the entire file, and then operate the file in the memory to read it; another method is to use seek () to move the file read/write pointer (file handle) in the file to read the file content; 1. Read the file from the memory: use the computer memory to read the content of the entire file, and then there are two ways to process the file content in the memory; the first method is to read a row of data from the file each time and store the data in a simple variable $ line, and then move the file read/write pointer to the second row; for example: $ line =; # Read a row of data from the file handle filehandle and store it to the simple variable $ line. The second method is to read all the content in the file to the array @ array in the unit of action, each row in the file (including a carriage return) serves as an element of the array @ array, and uses the subscript of the array to access different rows in the file; for example, @ array =; # Read all rows in the filehandle of the file handle to the array @ array in the unit of action, the operator for reading a file <> determines whether to read a row or all the content of the file based on the context. If the left side of the equal sign is a simple Scalar variable, the Read File operator <> reads only one row at a time and stores it in this simple variable. If the left side of the equal sign is an array, the file reading operator <> reads the content of the entire file in the array in units of rows (including carriage returns). Each row is an element of the array; if the Read File operator <> does not contain any parameters (that is, no file handle is included between "<" and "> ), by default, data is read from the standard input file handle stdin, that is, data is read from the command line through the keyboard. Each time a new row is read, the file input operator <> Returns 1; when the last row is read and then read, the file input operator returns a null value. This condition can be used to determine whether the pointer to the file's read/write position has reached the end of the file. This method is easy to use, applicable to small files, but it is not suitable if the file size is large. Seek () function can be used in this case; 2. Use seek () function to read files: Seek () A function reads or writes data to a file by moving the file read/write pointer using the file handle in bytes. It uses seek () the function can locate the next location where the program needs to read or write data. When a file is opened for reading, the file read/write position pointer stops at the beginning of the file, the read/write pointer of a file is automatically moved forward, and its position is the stop position of the read/write; When a file is opened for append, the read/write pointer of the file stops at the end of the file; when you need to transfer between the beginning and end of a file, you need to use the seek () function to locate the file read/write location; Seek () the function can freely move the file handle (file read/write pointer) position in the file. The seek () function has three basic positions: the beginning of the file (0), the current position (1) and (2) at the end of the file, you can specify the offset from these locations to specify the location of the file handle (file read/write pointer) to be moved in the file. the syntax of the seek () function is as follows: seek (filehandle, bytestoskip, startlocation); bytestoskip: indicates the number of bytes to be moved by the file handle (read/write position pointer); if the end is a positive number, it indicates moving to the end of the file; if it is a negative number, it indicates moving towards the file header. Note that the file handle (read/write position pointer) cannot be moved beyond the file header and end, that is: the file handle (read/write position pointer) can only be moved between the file header and the end of the file. Each English letter or punctuation occupies one byte, each Chinese Character and Chinese Punctuation each occupies two bytes. startlocaltion: indicates the starting position when the file handle (read/write position pointer) starts to move, optional values: 0, 1, and 2, indicating the beginning, current location, and end of the file respectively; filehandle: file handle to be operated; if the function is successfully called, a non-zero value (true) is returned. If the function fails, a zero value (false) is returned. It is often used with the tell () function () you do not have to close the file and re-open it between calls, which increases the reading speed of the file. 3. Tell () function: Use seek () one of the biggest disadvantages of using a function to locate a file read/write pointer is that it locates the file read/write pointer in bytes, which is less portable on different computers, the program may not run on other computers. To solve this problem, use the tell () function to extract the position pointed to by the file read/write position pointer. The syntax is as follows: $ position = tell (filehandle); Seek (filehandle, $ position, 0); this function is used to return the distance from the starting position of the file to the current read/write position (number of bytes ); note: Seek () and tell () functions cannot be used to point to the file variables of the pipeline; 4. File writing: the syntax for writing files is as follows: Print outflehandle (data); example: print outfilehandle ("Hello, Perl world/N"); to append data to a file, you only need to open the file in append mode before appending data: open (outfilehandle, "> FILENAME"); 5. File Modification: There are two ways to modify the file: one is to directly modify the file in the storage space of the hard disk; another method is to use memory as the space for modifying file content. When using memory, the speed is faster, but not suitable for ultra-large files. When using hard disk space, it is suitable for ultra-large files, but the speed is slow. When you use memory to modify a file, you only need to open the file in read/write mode. After opening the file, read the file content and then modify the read data, then, write the modified data directly to the corresponding location in the file. After the modification, close the file. Open (filehandle, "+ <FILENAME "); # open a file in read/write mode. Note: after using the file, remember to close the opened file. 6. Indirect file handle: for file operation functions such as open, close, print, printf, write, select, and EOF, you can use simple Scalar variables to replace the file handle parameters of these functions, the data stored in simple Scalar variables must be of the string type, and these strings are considered as the file handle name, file operation functions such as open, close, write, select, and EOF can also use expressions to replace file handles. However, the expression value must be a string and be used as the file handle name; with this feature, we can dynamically construct the file handle name by constructing strings at will to achieve the operation without using files; syntax for replacing file handle parameters with simple variables: $ filehandle = "infile"; $ openflag = open ($ filehandle, "filename1"); $ filehandle = "OUTFILE "; $ openflag = open ($ filehandle, "filename2"); in these statements, the value of the simple variable $ filehandle can be changed at will, the simple variable $ filehandle can open a file corresponding to the string and generate a corresponding file handle every time it obtains a different string. Note that: the values of these simple variables or expressions must be strings used as the file handle name;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.