Perl file operation

Perl manipulates a file using a variable called a file handle type.

A file handle is required to read or write data from a file.

The file handle is the name of an I/O connection.

Perl provides three file handles: STDIN, STDOUT, and STDERR, which represent standard inputs, standard outputs, and standard error outputs, respectively.

Opening a file in Perl can be used in the following ways:

open FILEHANDLE, EXPR
open FILEHANDLE

sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE

Description of the parameters:

  • FILEHANDLE: A file handle that holds a unique identifier for a file.
  • EXPR: An expression consisting of a file name and a file access type.
  • MODE: File access type.
  • PERMS: Access bits.

Open function

Here's the code We use the open function to open the file in a read-only .txt:

open(DATA, "<file.txt");

< Represents read-only mode.

The DATA in the code is the file handle used to read the file, and the following instances open the file and output the contents of the file:

#!/usr/bin/perl

open(DATA, "<file.txt") or die "file.txt 文件无法打开, $!";

while(<DATA>){
   print "$_";
}

The following code opens the file in a write .txt:

open(DATA, ">file.txt") or die "file.txt 文件无法打开, $!";

> Represents how the write is made.

If you need to open the file read and write, you can add a sign before the character:

open(DATA, "+<file.txt"); or die "file.txt 文件无法打开, $!";

This way does not delete the original contents of the file, if you want to delete it, in the following format:

open DATA, "+>file.txt" or die "file.txt 文件无法打开, $!";

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 文件无法打开, $!";

Means appending data to the tail of an existing file, and if you need to read the file content to be appended, you can add a plus sign:

open(DATA,"+>>file.txt") || die "file.txt 文件无法打开, $!";

The following table lists the different access patterns:

Mode Describe
or r Open in read-only mode and point the file pointer to the header of the file.
or w Write opens, points the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
or a Write opens, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
or r-plus Read and write open, pointing the file pointer to the file header.
or w Read and write open, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
Or a Read and write open, pointing the file pointer to the end of the file. If the file does not exist, try to create it.

Sysopen function

Sysopen functions are similar to open functions, but their arguments are not in the same form.

The following example opens a file by reading and writing ( .

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 O_CREAT to create a new file, O_WRONLY to write-only mode and O_RDONLY to read-only mode.

The PERMS parameter is an octal property value that represents the permissions of the file after it is created, and the default is 0x666.

The following table lists possible pattern values:

Mode Describe
O_RDWR Read and write open, pointing the file pointer to the file header.
O_RDONLY Open in read-only mode and point the file pointer to the header of the file.
O_WRONLY Write opens, points the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it.
O_CREAT Create a file
O_APPEND Append the file
O_TRUNC Cut the file size to zero
O_EXCL If a file O_CREAT the file, an error message is returned that tests for the existence of the file
O_NONBLOCK Non-blocking I/O makes our operation either successful or returns an error immediately and is not blocked.

Close function

After the file is finished, to close the file to refresh 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 true if it is successfully closed.

close(DATA) || die "无法关闭文件";

Read and write the file

There are several different ways to read and write information to a file:

THE operator of FILEHANDL

The primary way to read information from an open file handle is the operator of the fileHANDLE. I n the context of the calibration, it returns a single line from the file handle. For example:

#!/usr/bin/perl

print "W3Cschool教程网址?\n";
$name = <STDIN>;
print "网址:$name\n";

After the above program is executed, the following information is displayed, and the print statement outputs when we enter the URL:

Perl file operation

When we use the operator, it returns a list of each row in the file handle, for example, we can import all the rows into the array.

The implementation creates .txt import file, which reads:

$ cat import.txt 
1
2
3

Read the .txt and place each line in @lines array:

#!/usr/bin/perl

open(DATA,"<import.txt") or die "无法打开数据";
@lines = <DATA>;
print @lines;    # 输出数组内容
close(DATA);

The above procedure is performed and the output is:

1
2
3

Getc function

The xgetc function returns a single character from the specified FILEHANDLE, if STDIN is not specified:

getc FILEHANDLE
getc

If an error occurs, or if the file handle is at the end of the file, undef is returned.


Read function

The read function is used to read information from the file handle of the buffer.

This function is used to read binary data from a file.

read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH

Description of the parameters:

  • FILEHANDLE: A file handle that holds a unique identifier for a file.
  • SCALAR: Storage results, if OFFSET is not specified, the data will be placed at the beginning of THESCALAR. O therwise, the data is placed after the OFFSET byte in THESCALAR.
  • LENGTH: The length of the content read.
  • OFFSET: Offset.

If the read successfully returns the number of bytes read, if 0 is returned at the end of the file, if an error occurs, undef is returned.

The print function

For all functions that read information from a file handle, the main write function on the back end is print:

print FILEHANDLE LIST
print LIST
print

File handles and print functions allow you to send the results of a program run to an output device (STDOUT: standard output), for example:

print "Hello World!\n";

A copy of the file

In the following instance we will open an existing file file1 .txt and read each line of it and write it to file2.txt file:

#!/usr/bin/perl

# 只读方式打开文件
open(DATA1, "<file1.txt");

# 打开新文件并写入
open(DATA2, ">file2.txt");

# 拷贝数据
while(<DATA1>)
{
   print DATA2 $_;
}
close( DATA1 );
close( DATA2 );

The file is renamed

In the following example, we rename the existing file file1.txt to file2.txt, specifying that the directory is under /usr/youj/test/:

#!/usr/bin/perl

rename ("/usr/youj/test/file1.txt", "/usr/youj/test/file2.txt" );

The function renames accepts only two arguments and renames only existing files.

Delete the file

Here's an example of how to use the unlink function to delete a file:

#!/usr/bin/perl

unlink ("/usr/youj/test/file1.txt");

Specify the file location

You can use the tell function to get the location of the file and specify the location within the file by using the seek function:

The tell function

The tell function is used to get the file location:

tell FILEHANDLE
tell

If fileHANDLE is specified, the function returns the location of the file pointer in bytes. If not specified, the file handle selected by default is returned.

The seek function

The seek() function reads or writes to a file by moving the file read and write pointer through a file handle, read and write in bytes:

seek FILEHANDLE, POSITION, WHENCE

Description of the parameters:

  • FILEHANDLE: A file handle that holds a unique identifier for a file.
  • POSITION: Represents the number of bytes to be moved by the file handle (read and write position pointer).
  • WHENCE: Represents the starting position when the file handle (read and write position pointer) begins to move, with values of 0, 1, and 2;

The following instance reads 256 bytes from the beginning of the file:

seek DATA, 256, 0;

File information

Perl's file operations can also test for the existence of files, readability, etc.

Can I create a file1 .txt file file first, as follows:

$ cat file1.txt 
www.w3cschool.cn
#/usr/bin/perl

my $file = "/usr/test/youj/file1.txt";
my (@description, $size);
if (-e $file)
{
	push @description, '是一个二进制文件' if (-B _);
	push @description, '是一个socket(套接字)' if (-S _);
	push @description, '是一个文本文件' if (-T _);
	push @description, '是一个特殊块文件' if (-b _);
	push @description, '是一个特殊字符文件' if (-c _);
	push @description, '是一个目录' if (-d _);
	push @description, '文件存在' if (-x _);
	push @description, (($size = -s _)) ? "$size 字节" : '空';
	print "$file 信息:", join(', ',@description),"\n";
}

The above procedure is performed and the output is:

file1.txt 信息:是一个文本文件, 15 字节

The file test operator is shown in the following table:

Operator Describe
-A The last time a file was accessed (in days)
-B Whether it is a binary
-C The (inode) index node modification time of the file (in days)
-M The last time the file was modified (in days)
-O The file is allied to the real UID
-R A file or directory can be read by a real UID/GID
-S For socket (socket)
-T Whether it is a text file
-W A file or directory can be written by a real UID/GID
-X A file or directory can be executed by a real UID/GID
-b For block-special (special block) files (e.g. mounted disks)
-c For acter-special (special character) files (e.g. I/O devices)
-d is the directory
-e The file or directory name exists
-f is a normal file
-g A file or directory has setgid properties
-k The file or directory has a sticky bit set
-l is a symbolic link
-o The file is allied to the valid UID
-p File is Named Pipe (FIFO)
-r The file can be read by a valid UID/GID
-s File or directory exists and is not 0 (return bytes)
-t File handle is the return result of TTY (system function isatty(); this test cannot be used for file names)
-u The file or directory has setuid properties
-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), i.e. whether the file is empty,