Perl uses a variable called a file handle type to manipulate files.
Reading or writing data from a file requires a file handle.
A file handle is the name of an I/O connection.
Perl provides three file handles: STDIN, STDOUT, and STDERR, which represent standard input, standard output, and standard error output respectively.
You can open files in Perl using the following methods:
open FILEHANDLE, EXPRopen FILEHANDLE, FILENAME, MODE, PERMSsysopen FILEHANDLE, FILENAME, MODE
Parameter description:
FILEHANDLE: File handle, used to store a unique file identifier.
EXPR: An expression composed of file name and file access type.
MODE: file access type.
PERMS: access permission bits (permission bits).
In the following code, we use the open function to open the file file.txt in read-only mode (<):
open(DATA, "<file.txt");
< indicates read-only mode.
DATA in the code is the file handle used to read the file. The following example will open the file and output the file content:
The following code opens the file file.txt for writing ( > ):
open(DATA, ">file.txt") or die "file.txt file cannot be opened, $!";
> Indicates the writing method.
If you need to open the file for reading and writing, you can add a + sign before the > or < character:
open(DATA, "+<file.txt"); or die "file.txt file cannot be opened, $!";
This method will not delete the original content of the file. If you want to delete it, the format is as follows:
open DATA, "+>file.txt" or die "file.txt file cannot be opened, $!";
If you want to append data to a file, you only need to open the file in append mode before appending the data:
open(DATA,">>file.txt") || die "file.txt file cannot be opened, $!";
>> means appending data to the end of the existing file. If you need to read the content of the file to be appended, you can add the + sign:
open(DATA,"+>>file.txt") || die "file.txt file cannot be opened, $!";
The following table lists the different access modes:
model | describe |
---|---|
< or r | Open in read-only mode and point the file pointer to the file header. |
> or w | Open in writing mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. |
>> or a | Open in writing mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
+< or r+ | Open in read-write mode and point the file pointer to the file header. |
+> or w+ | Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. |
+>> or a+ | Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
The sysopen function is similar to the open function, except that their parameter forms are different.
The following example opens a file for reading and writing (+<filename):
sysopen(DATA, "file.txt", O_RDWR);
If you need to clear the file before updating it, the writing method is as follows:
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT to create a new file, O_WRONLY is write-only mode, O_RDONLY is read-only mode.
The PERMS parameter is an octal attribute value, indicating the permissions after file creation. The default is 0x666 .
The following table lists possible mode values:
model | describe |
---|---|
O_RDWR | Open in read-write mode and point the file pointer to the file header. |
O_RDONLY | Open in read-only mode and point the file pointer to the file header. |
O_WRONLY | Open in writing mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. |
O_CREAT | Create file |
O_APPEND | append file |
O_TRUNC | Truncate file size to zero |
O_EXCL | If the file exists when using O_CREAT, an error message will be returned. It can test whether the file exists. |
O_NONBLOCK | Non-blocking I/O allows our operation to either succeed or return an error immediately without being blocked. |
After the file is used, the file must be closed to refresh the input and output buffers associated with the file handle. The syntax for closing the file is as follows:
closeFILEHANDLEclose
FILEHANDLE is the specified file handle, and returns true if it is closed successfully.
close(DATA) || die "Cannot close file";
There are several different ways to read and write information to files:
The primary method of reading information from an open file handle is the <FILEHANDLE> operator. In a scalar context, it returns a single row from the file handle. For example:
When we use the <FILEHANDLE> operator, it will return a list of each line in the file handle, for example we can import all the lines into an array.
Implement the creation of the import.txt file with the following content:
$ cat import.txt 123
Read import.txt and put each line into the @lines array:
Executing the above program, the output result is:
123
The xgetc function returns a single character from the specified FILEHANDLE, or STDIN if not specified:
getcFILEHANDLEgetc
If an error occurs, or the file handle is at the end of the file, undef is returned.
The read function is used to read information from the buffer's file handle.
This function is used to read binary data from a file.
read FILEHANDLE, SCALAR, LENGTH, OFFSETread FILEHANDLE, SCALAR, LENGTH
Parameter description:
FILEHANDLE: File handle, used to store a unique file identifier.
SCALAR: Stores the result. If OFFSET is not specified, the data will be placed at the beginning of SCALAR. Otherwise the data is placed after the OFFSET byte in SCALAR.
LENGTH: The length of the read content.
OFFSET: offset.
Returns the number of bytes read if the read is successful, 0 if the end of file is reached, and undef if an error occurs.
For all functions that read information from file handles, the main writing function in the backend is print:
print FILEHANDLE LISTprint LISTprint
The results of program execution can be sent to the output device (STDOUT: standard output) using the file handle and the print function, for example:
print "Hello World!n";
In the following example, we will open an existing file file1.txt, read each line of it and write it to the file file2.txt:
In the following example, we rename the existing file file1.txt to file2.txt, and the specified directory is under /usr/codercto/test/:
#!/usr/bin/perlrename ("/usr/codercto/test/file1.txt", "/usr/codercto/test/file2.txt" );
The function renames only accepts two parameters and only renames existing files.
The following example demonstrates how to use the unlink function to delete files:
You can get the location of a file using the tell function, and specify the location within the file by using the seek function:
The tell function is used to get the file location:
tell FILEHANDLEtell
If FILEHANDLE is specified, this function returns the position of the file pointer, in bytes. If not specified, returns the default selected file handle.
The seek() function reads or writes files by moving the file read-write pointer through the file handle, and reads and writes in bytes:
seek FILEHANDLE, POSITION, WHENCE
Parameter description:
FILEHANDLE: File handle, used to store a unique file identifier.
POSITION: Indicates the number of bytes to be moved by the file handle (read and write position pointer).
WHENCE: Indicates the starting position when the file handle (read-write position pointer) starts to move. The possible values are 0, 1, and 2; indicating the beginning of the file, the current position, and the end of the file respectively.
The following example reads 256 bytes from the beginning of the file:
seek DATA, 256, 0;
Perl's file operations can also first test whether the file exists, whether it can be read and written, etc.
We can first create the file1.txt file, as follows:
$ cat file1.txt www.codercto.com
Executing the above program, the output result is:
file1.txt information: is a text file, 15 bytes
The file test operators are shown in the following table:
Operator | describe |
---|---|
-A | The time when the file was last accessed (unit: days) |
-B | Is it a binary file? |
-C | File (inode) index node modification time (unit: days) |
-M | The time when the file was last modified (unit: days) |
-O | File is owned by real UID |
-R | Files or directories can be read by real UID/GID |
-S | For socket (socket) |
-T | Is it a text file? |
-W | Files or directories can be written to with real UID/GID |
-X | Files or directories can be executed with real UID/GID |
-b | For block-special (special block) files (such as mounted disks) |
-c | For character-special (special character) files (such as I/O devices) |
-d | for directory |
-e | The file or directory name exists |
-f | for ordinary files |
-g | File or directory has setgid attribute |
-k | The file or directory has the sticky bit set |
-l | for symbolic links |
-o | File is owned by a valid UID |
-p | The file is a named pipe (FIFO) |
-r | File can be read with valid UID/GID |
-s | The file or directory exists and is not 0 (returns the number of bytes) |
-t | The file handle is TTY (return result of system function isatty(); this test cannot be used for file names) |
-u | File or directory has setuid attribute |
-w | Files can be written to with valid UID/GID |
-x | File can be executed with a valid UID/GID |
-z | The file exists and the size is 0 (the directory is always false), that is, whether it is an empty file. |