Perl file operation
Perl
use a variable called the file handle type to manipulate the file.
A file handle is required to read or write data from a file.
The file handle (file handle) is the name of an Icano connection.
Perl
provides three types of file handles: STDIN
, STDOUT
, and STDERR
, representing standard input, standard output, and standard error output, respectively.
Perl
can open a file in the following ways:
open FILEHANDLE, EXPR
open FILEHANDLE
sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE
Parameter description:
FILEHANDLE
:A file handle that holds a unique identifier of a fileEXPR
:An expression consisting of a file name and a file access typeMODE
:File access typePERMS
:Access permission bit (permission bits)
Open function
The following code we use open
the function opens the file as read-only (<) file.txt
:
open(DATA, "<file.txt");
<
represents read-only mode.
In the code DATA
for the file handle to read the file, the following example opens the file and outputs the contents of the file:
Example
#!/usr/bin/perlopen(DATA,"<file.txt")ordie"file.txt
File cannot be opened,$!";while(<DATA>){print"$\_";}
The following code opens the file file.txt as a write (>):
open(DATA, ">file.txt") or die "file.txt File cannot be opened, $!";
>
indicates how it is written.
If you need to open the file in read-write mode, you can open it in the >
or <
add before character +
number:
open(DATA, "+<file.txt"); or die "file.txt File cannot be opened, $!";
This method does not delete the original contents 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 as an append before appending the data:
open(DATA,">>file.txt") || die "file.txt File cannot be opened, $!";
>>
means to append data to the end of an existing file. If you need to read the contents of the file to be appended, you can add it. +
number:
open(DATA,"+>>file.txt") || die "file.txt File cannot be opened, $!";
The following table lists the different access modes:
Pattern |
Description |
---|---|
< or r |
Open read-only and point the file pointer to the file header. |
> or w |
Open in 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 write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
+< 或 r+ |
Open it in read-write mode and point the file pointer to the file header. |
+> 或 w+ |
Open read-write, 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. |
+>> 或 a+ |
Open read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
Sysopen function
sysopen
function is similar to open
functions, but their arguments are not the same.
The following example opens the file with read-write (+ < filename):
sysopen(DATA, "file.txt", O_RDWR);
If you need to empty the file before updating it, write as follows:
sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );
You can use O_CREAT
to create a new file O_WRONLY
for write-only mode O_RDONLY
in read-only mode.
The PERMS
parameter is an octal attribute value, which represents the permissions after the file is created. The default is 0x666
.
The following table lists the possible pattern values:
Pattern |
Description |
---|---|
O_RDWR |
Open it in read-write mode and point the file pointer to the file header. |
O_RDONLY |
Open read-only and point the file pointer to the file header. |
O_WRONLY |
Open in 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. |
O_CREAT |
Create a file |
O_APPEND |
Append file |
O_TRUNC |
Truncate the file size to zero |
O_EXCL |
If using O_CREAT when the file exists, an error message is returned, which can test whether the file exists |
O_NONBLOCK |
Non-blocking I/O makes our operation either successful or immediately return an error without blocking. |
Close function
After the file is used, to close the file to flush the input and output buffer associated with the file handle, the syntax for closing the file is as follows:
close FILEHANDLE
close
FILEHANDLE
is the specified file handle, and returns if closed successfully true
.
close(DATA) || die "cannot close file";
Read and write files
There are several different ways to read and write information to a file:
< FILEHANDL > operator
The main way to read information from an open file handle is <FILEHANDLE>
operator. In a scalar context, it returns a single line from the file handle. For example:
Example
#!/usr/bin/perlprint"Novice Tutorial website?\\n";$name=
<STDIN>;print"website:$name\\n";
After the above procedure is executed, the following information will be displayed. After we enter the URL, print
statement will output:
When we use the <FILEHANDLE>
operator, it returns a list of each line in the file handle, for example, we can import all rows into the array.
Implementation creation import.txt
file, the contents are as follows:
$ cat import.txt
1
2
3
Read import.txt
And put each line into @lines
array:
Example
#!/usr/bin/perlopen(DATA,"<import.txt")ordie"Unable to open data";@lines=
<DATA>;print@lines;# Output array contentclose(DATA);
Execute the above program, and the output is as follows:
1
2
3
Getc function
xgetc
function from the specified FILEHANDLE
returns a single character, if it is not specified STDIN
:
getc FILEHANDLE
getc
If an error occurs, or if the file handle is at the end of the file, return``undef`` .
Read function
read
function is used to read information from the file handle of the buffer.
This function is used to read binary data from files.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
Parameter description:
FILEHANDLE
:A file handle that holds a unique identifier of a fileSCALAR
: store the results, if not specifiedOFFSET
the data will be placed in the beginning ofSCALAR
. Otherwise, the data is placed intheSCALAR
inOFFSET
after the byte.LENGTH
:The length of the content readOFFSET
: offset.
If the read is successful, the number of bytes read is returned, if 0 is returned at the end of the file, and if an error occurs undef
.
Print function
For all functions that read information from a file handle, the main write function at the back end is print
:
print FILEHANDLE LIST
print LIST
print
Using file handles and print
function can send the result of the program to the output device (STDOUT: standard output), for example:
print "Hello World!\n";
File copy
For the following example, we will open an existing file file1.txt
and read every line of it written to the file file2.txt
:
Example
#!/usr/bin/perl# Open file in read-only mode open(DATA1,"<file1.txt");#
Open a new file and write to it open(DATA2,">file2.txt");#
Copy Data while(<DATA1>){printDATA2$\_;}close(DATA1);close(DATA2);
File renaming
For the following example, we will have an existing file file1.txt
rename to file2.txt
, the specified directory is in the /usr/runoob/test/
below:
#!/usr/bin/perl
rename ("/usr/runoob/test/file1.txt", "/usr/runoob/test/file2.txt" );
Function renames
only two parameters are accepted and only existing files are renamed.
Delete a file
The following example shows how to use the unlink
function to delete the file:
Example
#!/usr/bin/perlunlink("/usr/runoob/test/file1.txt");
Specify the file location
You can use it. tell
function to get the location of the file and by using the seek
function to specify the location within the file:
Tell function
tell
function is used to get the file location:
tell FILEHANDLE
tell
If you specify FILEHANDLE
this function returns the position of the file pointer, in bytes. If not specified, the default selected file handle is returned.
Seek function
seek()
function reads or writes a file by moving the file read-write pointer through the file handle, reading and writing in bytes:
seek FILEHANDLE, POSITION, WHENCE
Parameter description:
FILEHANDLE
:A file handle that holds a unique identifier of a filePOSITION
:Represents the number of bytes to be moved by the file handle (read-write position pointer)WHENCE
:Represents the starting position of the file handle (read-write position pointer) when it starts to move. The values you can take are 0, 1, and 2; they represent the beginning of the file, the current location, and the end of the file, respectively.
The following example reads 256 bytes from the beginning of the file:
seek DATA, 256, 0;
File information
The Perl
file operation can also test whether the file exists, whether it can be read or written, and so on.
We can first create file1.txt
document is as follows:
$ cat file1.txt
www.runoob.com
Example
#/usr/bin/perlmy$file="/usr/test/runoob/file1.txt";my(@description,$size);if(-e$file){push@description,
'it is a binary file'if(-B\_);push@description,'it is a socket (socket)'if(-S\_);push@description,
'it is a text file'if(-T\_);push@description,'it is a special block file'if(-b\_);push@description,
'it is a special character file'if(-c\_);push@description,'it is a directory'if(-d\_);push@description,
'file exists'if(-x\_);push@description,(($size=
-s\_))?"$size byte":'blank';print"$file information:",join(',',@description),"\\n";}
Execute the above program, and the output is as follows:
file1.txt information: It is a text file with 15 bytes
The file test operator is shown in the following table:
Operator |
Description |
---|---|
A |
Time when the file was last accessed (in days) |
-B |
Whether it is a binary file |
-C |
File’s (inode) Inode modification time (in days) |
-M |
Time when the file was last modified (in days) |
-O |
The file is owned by the real UID |
-R |
Files or directories can be read by real UID/GID |
-S |
Socket |
-T |
Whether it is a text file |
-W |
A file or directory can be written by a real UID/GID |
-X |
Files or directories can be executed by a real UID/GID |
-b |
Is a block-special (special block) file (such as mounting a disk) |
-c |
Is a character-special (special character) file (such as an Icano device) |
-d |
For the catalog |
-e |
File or directory name exists |
-f |
Is an ordinary file |
-g |
A file or directory has a setgid attribute |
-k |
The sticky bit is set in the file or directory |
-l |
For symbolic links |
-o |
Files are owned by valid UID |
-p |
The file is a named pipe (FIFO) |
-r |
The file can be read by a valid UID/GID |
S |
File or directory exists and is not 0 (number of bytes returned) |
-t |
The file handle is TTY (the return result of the system function isatty (); you cannot use this test on the file name) |
-u |
A file or directory has a setuid attribute |
-w |
Files can be written by a valid UID/GID |
-x |
Files can be executed by a valid UID/GID |
-z |
The file exists with a size of 0 (the directory is always false), that is, whether it is an empty file |