Perl 简明教程

Perl - File I/O

文件处理的基本原理很简单:将 filehandle 与一个外部链接(通常是一个文件)关联起来,然后使用 Perl 中的各种操作符和函数在与文件句柄关联的数据流中读取和更新存储的数据。

文件句柄是关联物理文件和名称的已命名的 Perl 内部结构。所有文件句柄都具有读/写访问权限,因此你可以读取和更新与文件句柄关联的任何文件或设备。但是,当你关联一个文件句柄时,你可以指定文件句柄的打开模式。

三个基本文件句柄是 - STDINSTDOUTSTDERR, ,它们分别代表标准输入、标准输出和标准错误设备。

Opening and Closing Files

有两个带有多种形式的基本函数,可用于在 Perl 中打开任何新文件或现有文件。

open FILEHANDLE, EXPR
open FILEHANDLE

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

此处的 FILEHANDLE 是由 open 函数返回的文件句柄,EXPR 是具有文件名和文件打开模式的表达式。

Open Function

以下是在只读模式下打开 file.txt 的语法。此处的小于 < 符号表示该文件必须在只读模式下打开。

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

这里 DATA 是文件句柄,其将用于读文件。这里有一个示例,它将打开一个文件并在屏幕上打印其内容。

#!/usr/bin/perl

open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!";

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

以下是在写入模式下打开 file.txt 的语法。此处的小于 > 符号表示该文件必须在写入模式下打开。

open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!";

此示例实际上在打开文件进行写入之前截短(清空)该文件,但这可能不是预期的效果。如果想要以读写方式打开文件,你可以在 > 或 < 字符之前加上一个加号。

例如,要在不截断文件的情况下以更新模式打开文件 −

open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";

要先截断文件 −

open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!";

你可以以追加模式打开文件。在此模式下,写入点将设置到文件的末尾。

open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!";

双 >> 以追加方式打开文件,将文件指针放在末尾,这样你就可以立即开始追加信息。但是,除非你在它的前面也加上一个加号,否则你无法从中读取 −

open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!";

下表给出了不同模式的可能值

Sr.No.

Entities & Definition

1

&lt; or r 只读访问

2

&gt; or w 创建、写入和截断

3

&gt;&gt; or a 写入、追加和创建

4

&lt; or r 读写

5

&gt; or w 读、写、创建和截断

6

>> or a Reads, Writes, Appends, and Creates

Sysopen Function

The sysopen function is similar to the main open function, except that it uses the system open() function, using the parameters supplied to it as the parameters for the system function −

For example, to open a file for updating, emulating the +<filename format from open −

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

Or to truncate the file before updating −

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

You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY - to open file in read only mode.

The PERMS argument specifies the file permissions for the file specified, if it has to be created. By default it takes 0x666.

Following is the table, which gives the possible values of MODE.

Sr.No.

Entities & Definition

1

O_RDWR Read and Write

2

O_RDONLY Read Only

3

O_WRONLY Write Only

4

O_CREAT Create the file

5

O_APPEND Append the file

6

O_TRUNC Truncate the file

7

O_EXCL Stops if file already exists

8

O_NONBLOCK Non-Blocking usability

Close Function

To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle’s buffers and closes the system’s file descriptor.

close FILEHANDLE
close

If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only if it could successfully flush the buffers and close the file.

close(DATA) || die "Couldn't close file properly";

Reading and Writing Files

Once you have an open filehandle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file.

The <FILEHANDL> Operator

The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example −

#!/usr/bin/perl

print "What is your name?\n";
$name = <STDIN>;
print "Hello $name\n";

When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array −

#!/usr/bin/perl

open(DATA,"<import.txt") or die "Can't open data";
@lines = <DATA>;
close(DATA);

getc Function

The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified −

getc FILEHANDLE
getc

If there was an error, or the filehandle is at end of file, then undef is returned instead.

read Function

The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file.

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

The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error.

print Function

For all the different methods used for reading information from filehandles, the main function for writing information back is the print function.

print FILEHANDLE LIST
print LIST
print

The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example −

print "Hello World!\n";

Copying Files

Here is the example, which opens an existing file file1.txt and read it line by line and generate another copy file file2.txt.

#!/usr/bin/perl

# Open file to read
open(DATA1, "<file1.txt");

# Open new file to write
open(DATA2, ">file2.txt");

# Copy data from one file to another.
while(<DATA1>) {
   print DATA2 $_;
}
close( DATA1 );
close( DATA2 );

Renaming a file

Here is an example, which shows how we can rename a file file1.txt to file2.txt. Assuming file is available in /usr/test directory.

#!/usr/bin/perl

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

This function renames takes two arguments and it just renames the existing file.

Deleting an Existing File

Here is an example, which shows how to delete a file file1.txt using the unlink function.

#!/usr/bin/perl

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

Positioning inside a File

You can use to tell function to know the current position of a file and seek function to point a particular position inside the file.

tell Function

The first requirement is to find your position within a file, which you do using the tell function −

tell FILEHANDLE
tell

This returns the position of the file pointer, in bytes, within FILEHANDLE if specified, or the current default selected filehandle if none is specified.

seek Function

The seek function positions the file pointer to the specified number of bytes within a file −

seek FILEHANDLE, POSITION, WHENCE

The function uses the fseek system function, and you have the same ability to position relative to three different points: the start, the end, and the current position. You do this by specifying a value for WHENCE.

Zero sets the positioning relative to the start of the file. For example, the line sets the file pointer to the 256th byte in the file.

seek DATA, 256, 0;

File Information

You can test certain features very quickly within Perl using a series of test operators known collectively as -X tests. For example, to perform a quick test of the various permissions on a file, you might use a script like this −

#/usr/bin/perl

my $file = "/usr/test/file1.txt";
my (@description, $size);
if (-e $file) {
   push @description, 'binary' if (-B _);
   push @description, 'a socket' if (-S _);
   push @description, 'a text file' if (-T _);
   push @description, 'a block special file' if (-b _);
   push @description, 'a character special file' if (-c _);
   push @description, 'a directory' if (-d _);
   push @description, 'executable' if (-x _);
   push @description, (($size = -s _)) ? "$size bytes" : 'empty';
   print "$file is ", join(', ',@description),"\n";
}

Here is the list of features, which you can check for a file or directory −

Sr.No.

Operator & Definition

1

-A Script start time minus file last access time, in days.

2

-B Is it a binary file?

3

-C Script start time minus file last inode change time, in days.

3

-M Script start time minus file modification time, in days.

4

-O Is the file owned by the real user ID?

5

-R Is the file readable by the real user ID or real group?

6

-S Is the file a socket?

7

-T Is it a text file?

8

-W Is the file writable by the real user ID or real group?

9

-X Is the file executable by the real user ID or real group?

10

-b Is it a block special file?

11

-c Is it a character special file?

12

-d Is the file a directory?

13

-e Does the file exist?

14

-f Is it a plain file?

15

-g Does the file have the setgid bit set?

16

-k Does the file have the sticky bit set?

17

-l Is the file a symbolic link?

18

-o Is the file owned by the effective user ID?

19

-p Is the file a named pipe?

20

-r Is the file readable by the effective user or group ID?

21

-s Returns the size of the file, zero size = empty file.

22

-t Is the filehandle opened by a TTY (terminal)?

23

-u Does the file have the setuid bit set?

24

-w Is the file writable by the effective user or group ID?

25

-x Is the file executable by the effective user or group ID?

26

-z Is the file size zero?