Perl File Operations
Perl uses a type of variable called a filehandle to operate on files.
Reading data from or writing data to a file requires a file handle.
**Filehandle (file handle)** is a I/O name of a connection.
Perl provides three filehandles: STDIN, STDOUT, STDERR, representing respectivelyStandard input、Standard outputandstandard error output。
In Perl, files can be opened in the following ways:
open FILEHANDLE, EXPR
open FILEHANDLE
sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE
Parameter description:
- FILEHANDLE: the filehandle, used to store a unique identifier for a file.
- EXPR: an expression consisting of the file name and the file access type.
- MODE: the file access type.
- PERMS: permission bits.
The open Function
In the following code we use the open function in read-only mode < to open the file file.txt:
open(DATA, "
< means read-only mode.
In the code, DATA is the file handle used to read the file; the following example will open a file and output its contents:
Example
#!/usr/bin/perl
open
(
DATA
,
"
" ) or die " The file.txt file cannot be opened, $! " ; while ( ; } The following code opens the file file.txt in write (>) mode: Indicates write mode. If you need to open a file for both reading and writing, you can add a + sign before the > or < character: This method does not delete the original contents of the file; if you want to delete them, the format is as follows: If you want to append data to a file, before appending the data you only need to open the file in append mode: Indicates appending data to the end of an existing file; if you need to read the contents of the file to be appended, you can add a + sign: The following table lists the different access modes: sysopen functions are similar to the open function, except that their parameter forms are different. The following example opens a file for reading and writing (+ If you need to clear the file before updating it, write it as follows: You can use O_CREAT to create a new file, O_WRONLY for write-only mode, and O_RDONLY for read-only mode. The PERMS The parameter is an octal attribute value that represents the permissions of the file after it is created, defaulting to 0x666。 The following table lists the possible mode values: After you are finished using a file, you should close it to flush the input/output buffers associated with the file handle. The syntax for closing a file is as follows: FILEHANDLE is the specified file handle; returns true if it is closed successfully. There are several different ways to read from and write to a file: The main method for reading information from an open file handle is #!/usr/bin/perl print " Runoob Tutorial URL? \n " ; $name = < STDIN ; print " URL: $name \n " ; After the above program is executed, the following information will be displayed; after we enter a URL, the print statement will output: When we use This implements creating the import.txt file, with the content as follows: Read import.txt and put each line into the @lines array: #!/usr/bin/perl open ( DATA , " " ) or die " Unable to open data " ; @lines = < DATA ; print @lines ; close ( DATA ) ; Running the above program, the output is: The xgetc function returns a single character from the specified FILEHANDLE, or from STDIN if none is specified: If an error occurs, or if the file handle is at the end of the file, undef is returned. The read function is used to read information from a buffered file handle. This function is used to read binary data from a file. Parameter description: If the read succeeds, the number of bytes read is returned; if at the end of the file, 0 is returned; if an error occurs, undef is returned. For all functions that read information from a file handle, the main writing function on the back end is print: Using a filehandle and the print function, you can send the results of a program to an output device (STDOUT: standard output), for example: The following example opens an existing file file1.txt, reads each of its lines, and writes them to the file file2.txt: #!/usr/bin/perl open ( DATA1 , " " ) ; open ( DATA2 , " file2.txt " ) ; while ( ; } close ( DATA1 ) ; close ( DATA2 ) ; The following example renames the existing file file1.txt to file2.txt, with the specified directory under /usr/runoob/test/: function renames accepts only two parameters and only renames files that already exist. The following example demonstrates how to use unlink function to delete a file: #!/usr/bin/perl unlink ( " /usr/runoob/test/file1.txt " ) ; You can use the tell function to get the position of a file, and by using seek function to specify the position within a file: The tell function is used to get the file position: If FILEHANDLE is specified, the function returns the position of the file pointer, in bytes. If it is not specified, the default selected file handle is returned. The seek() function reads from or writes to a file by moving the file read/write pointer through the file handle, with reading and writing performed in bytes: Parameter description: The following example reads 256 bytes from the beginning of the file: File operations in Perl can also first test whether a file exists and whether it is readable or writable, and so on. We can first create the file1.txt file, with the content as follows: #/usr/bin/perl my $file = " /usr/test/runoob/file1.txt " ; my ( @description , $size ) ; if ( e $file ) { push @description , ' is a binary file ' if ( B _ ) ; push @description , ' is a socket ' if ( S _ ) ; push @description , ' is a text file ' if ( T _ ) ; push @description , ' is a special block file ' if ( b _ ) ; push @description , ' is a special character file ' if ( c _ ) ; push @description , ' is a directory ' if ( d _ ) ; push @description , ' if the file exists ' if ( x _ ) ; push @description , ( ( $size = - s _ ) ) ? " $size bytes " : ' null ' ; print " $file Information: " , join ( ' , ' , @description ) , " \n " ; } Running the above program, the output is: The file test operators are shown in the following table:<
DATA
)
{
print
"
$_
"
open(DATA, ">file.txt") or die "file.txt 文件无法打开, $!";
open(DATA, "+
open DATA, "+>file.txt" or die "file.txt 文件无法打开, $!";
open(DATA,">>file.txt") || die "file.txt 文件无法打开, $!";
open(DATA,"+>>file.txt") || die "file.txt 文件无法打开, $!";
Mode
Description
< or r
Open for reading, with the file pointer positioned at the beginning of the file.
> or w
Open for writing, with the file pointer positioned at the beginning of the file and the file size truncated to zero. If the file does not exist, an attempt is made to create it.
>> or a
Open for writing, with the file pointer positioned at the end of the file. If the file does not exist, an attempt is made to create it.
+< or r+
Open for reading and writing, with the file pointer positioned at the beginning of the file.
+> or w+
Open for reading and writing, position the file pointer at the beginning of the file and truncate the file size to zero. If the file does not exist, attempt to create it.
+>> or a+
Open for reading and writing, with the file pointer positioned at the end of the file. If the file does not exist, attempt to create it.
Sysopen Function
sysopen(DATA, "file.txt", O_RDWR);
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
Mode
Description
O_RDWR
Open for reading and writing, with the file pointer positioned at the beginning of the file.
O_RDONLY
Open for reading, with the file pointer positioned at the beginning of the file.
O_WRONLY
Open for writing, with the file pointer positioned at the beginning of the file and the file size truncated to zero. If the file does not exist, an attempt is made to create it.
O_CREAT
Create a file
O_APPEND
Appending to a File
O_TRUNC
Truncate the file size to zero
O_EXCL
If O_CREAT is used and the file already exists, an error message is returned; it can be used to test whether a file exists
O_NONBLOCK
Non-blocking I/O makes our operations either succeed or return an error immediately, without being blocked.
Close Function
close FILEHANDLE
close
close(DATA) || die "无法关闭文件";
Reading and writing files
Example

$ cat import.txt
1
2
3
Example
Output the array contents
1
2
3
getc function
getc FILEHANDLE
getc
read function
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
print function
print FILEHANDLE LIST
print LIST
print
print "Hello World!\n";
File copy
Example
Open a file in read-only mode
Open a new file and write to it
Copy Data
<
DATA1
)
{
print
DATA2
$_File renaming
#!/usr/bin/perl
rename ("/usr/runoob/test/file1.txt", "/usr/runoob/test/file2.txt" );
Delete a file
Example
Specify File Position
tell function
tell FILEHANDLE
tell
seek function
seek FILEHANDLE, POSITION, WHENCE
seek DATA, 256, 0;
File information
$ cat file1.txt
www.runoob.com
Example
file1.txt 信息:是一个文本文件, 15 字节
Operator
Description
-A
The time since the file was last accessed (in days)
-B
whether it is a binary file
-C
The (inode) index node modification time of the file (in days)
-M
The time the file was last modified (in days)
-O
File is owned by the real UID
-R
File or directory is readable by the real UID/GID
-S
for socket (socket)
-T
whether it is a text file
-W
File or directory is writable by the real UID/GID
-X
File or directory is executable by the 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 directories
-e
File or directory name exists
-f
for regular files
-g
File or directory has the setgid attribute set
-k
File or directory has the sticky bit set
-l
for symbolic links
-o
File is owned by the effective UID
-p
File is a named pipe (FIFO)
-r
File is readable by the effective UID/GID
-s
File or directory exists and has a non-zero size (returns the number of bytes)
-t
File handle is a TTY (the result of the system function isatty(); this test cannot be used on a filename)
-u
File or directory has the setuid attribute set
-w
File is writable by the effective UID/GID
-x
File is executable by the effective UID/GID
-z
File exists and has a size of zero (always false for directories), that is, whether it is an empty file,