Latest web development tutorials

Perl file operations

Perl uses a technique called variable file handle to operate the type of file.

Read or write data from a file requires the use of file handles.

File handle (file handle) is the name of an I / O connections.

Perl provides three file handles: STDIN, STDOUT, STDERR, representing standard input, standard output and standard error output.

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: file handles, used to store a unique identifier for the file.
  • EXPR: file name and file access type consisting of expression.
  • MODE: file access type.
  • PERMS: Access Bit (permission bits).

Open function

We use the following code function to open a read-only mode (<) to open the file file.txt:

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

<Read-only representation.

Code DATA file handle is used to read the file, the following example will open the file and the file contents of the output:

#!/usr/bin/perl

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

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

The following code to write (>) way to open the file file.txt:

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

> For write mode.

If you need to open the file in read-write mode, in front> or <character + sign to add:

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

This approach does not delete the original file content, if you want to delete the following format:

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

If you want to file additional data, the additional data before, you only need to open the file in append mode:

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

>> Represents append data to the existing file, if you need to read the contents of a file to append to add the + sign:

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

The following table lists the different access modes:

mode description
<Or r Open for reading only the file pointer to the file header.
> Or w Open for writing the file pointer to the file header and the file size is cut to zero. If the file does not exist, attempt to create.
>> Or a Open for writing the file pointer at the end of the file. If the file does not exist, attempt to create.
+ <Or r + Open for reading and writing, the file pointer to the file header.
+> Or w + Open for reading and writing, the file pointer to the file header and the file size is cut to zero. If the file does not exist, attempt to create.
>> + Or a + Open for reading and writing the file pointer at the end of the file. If the file does not exist, attempt to create.

Sysopen function

sysopen function is similar to open function, but they are not the same form of argument.

The following example is based on reading and writing (+ <filename) way to open the file:

sysopen(DATA, "file.txt", O_RDWR);

If you need to update files emptied before the file is written as follows:

sysopen(DATA, "file.txt", O_RDWR|O_TRUNC );

You can use the O_CREAT to create a new file, O_WRONLY write-only mode, O_RDONLY read-only mode.

The PERMS parameters octal property value indicates that the file permissions after creation, the default is 0x666.

The following table lists the possible mode values:

mode description
O_RDWR Open for reading and writing, the file pointer to the file header.
O_RDONLY Open for reading only the file pointer to the file header.
O_WRONLY Open for writing the file pointer to the file header and the file size is cut to zero. If the file does not exist, attempt to create.
O_CREAT Create a file
O_APPEND Append File
O_TRUNC The file size is cut to zero
O_EXCL If you are using O_CREAT file exists, it returns an error message, it can test whether a file exists
O_NONBLOCK Non-blocking I / O operations so that we either succeed or immediately returns an error, not blocked.

Close function

After use in the file, close the file you want to refresh the file handle input and output buffers associated with closing the file has the following syntax:

close FILEHANDLE
close

FILEHANDLE for the specified file handle, if successfully closed returns true.

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

Reading and Writing Files

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

<FILEHANDL> operator

The main method of reading information from an open file handle is <FILEHANDLE> operator. In scalar context, it returns a single line from the file handle. E.g:

#!/usr/bin/perl

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

After the implementation of the above procedure, the following information, we will enter the URL print statement output:

When we use <FILEHANDLE> operator, which returns a file handle for each row in the list, for example, we can import all of the lines to the array.

Implementation creates import.txt file, as follows:

$ cat import.txt 
1
2
3

Import.txt and read each line into @lines array:

#!/usr/bin/perl

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

The above program, the output is:

1
2
3

getc function

xgetc function returns a single character from the specified FILEHANDLE, if you do not specify a return STDIN:

getc FILEHANDLE
getc

If an error occurs, or the file handle at the end of the file, it returns undef.


read function

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

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

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

Parameter Description:

  • FILEHANDLE: file handles, used to store a unique identifier for the file.
  • SCALAR: Start reading position.
  • LENGTH: content length read.
  • OFFSET: offset.

If successful return to read the number of bytes read, returns 0 if the end of the file, if an error occurs return undef.

print function

For all the information is read from the file handle functions at the rear end of the main function is to write print:

print FILEHANDLE LIST
print LIST
print

Use file and print functions can handle the results of running to the output apparatuses (STDOUT: standard output), for example:

print "Hello World!\n";

File copy

The following example we will open an existing file file1.txt, and read it each line written to the file file2.txt in:

#!/usr/bin/perl

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

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

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

Rename the file

The following examples, we'll already existing file file1.txt rename file2.txt, directory specified in the / usr / w3big / test / under:

#!/usr/bin/perl

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

Functionrenames only accepts two parameters, only the file already exists will be renamed.

Delete Files

The following examples demonstrate how we use theunlink function to delete this file:

#!/usr/bin/perl

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

Specify the file location

You can use thetell function to get the location of the file, and specify location within the file by using the seekfunction:

tell function

tell function is used to obtain the file location:

tell FILEHANDLE
tell

If FILEHANDLE the function returns the position of the file pointer, in bytes. If you do not specify a return to the default selected file handle.

seek function

seek () function is used to move through the file handle file read and write pointers the way to read or write a file, in bytes read and write:

seek FILEHANDLE, POSITION, WHENCE

Parameter Description:

  • FILEHANDLE: file handles, used to store a unique identifier for the file.
  • POSITION: indicates the number of bytes of file handle (read-write position pointer) to move.
  • WHENCE: represents a file handle (read-write location pointers) start when the starting position, you can take a value of 0, 1; denote the beginning of the file, the current position and the end of the file.

The following examples are to read 256 bytes from the beginning of the file:

seek DATA, 256, 0;

File information

Perl file operations also can test whether a file exists and is reading and writing.

What I can create file1.txt file, such as within the following:

$ cat file1.txt 
www.w3big.com
#/usr/bin/perl

my $file = "/usr/test/w3big/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 program, the output is:

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

File test operators in the following table:

Operators description
-A The file is first accessed time (units: days)
-B Whether it is a binary file
-C File (inode) inode modification time (units: days)
-M The file were last modified time (units: days)
-O All files are real UID
-R File or directory can be read by real UID / GID
-S The socket (Socket)
-T Whether it is a text file
-W File or directory can be written to the real UID / GID
-X Files or directories can be executed real UID / GID
-b A block-special (special block) file (such as mount disk)
-c The character-special (special characters) file (such as I / O devices)
-d Directory
-e File or directory name exists
-f Ordinary file
-g File or directory has the setgid attribute
-k File or directory has the sticky bit
-l It is a symbolic link
-o All files are valid UID
-p File is a named pipe (FIFO)
-r Files can be effectively UID / GID read
-s File or directory exists and is not 0 (returns the number of bytes)
-t File handle is TTY (system function isatty () returns the result; the file name can not use this test)
-u File or directory has the setuid attribute
-w Files can be written to a valid UID / GID
-x Files can be executed effectively UID / GID
-z File exists, the size of 0 (constant directory is false), that is, whether the file is empty,