Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl File Operations

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:


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

(

<

DATA

)

{

print

"

$_

"

;

}

The following code opens the file file.txt in write (>) mode:



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

Indicates write mode.

If you need to open a file for both reading and writing, you can add a + sign before the > or < character:



open(DATA, "+

This method does not delete the original contents of the file; if you want to delete them, the format is as follows:



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

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

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

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:



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

The following table lists the different access modes:

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 functions are similar to the open function, except that their parameter forms are different.

The following example opens a file for reading and writing (+



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

If you need to clear the file before updating it, write it 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, 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:

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

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:



close FILEHANDLE

close

FILEHANDLE is the specified file handle; returns true if it is closed successfully.



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


Reading and writing files

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

Operator

The main method for reading information from an open file handle is operator. In scalar context, it returns a single line from the file handle. For example:

Example

#!/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 When using the operator, it returns a list of every line in the file handle, for example we can import all the lines into an array.

This implements creating the import.txt file, with the content as follows:



$ cat import.txt 

1

2

3

Read import.txt and put each line into the @lines array:

Example

#!/usr/bin/perl

open

(

DATA

,

"

"

)

or

die

"

Unable to open data

"

;

@lines

= <

DATA

;

print

@lines

;

Output the array contents

close

(

DATA

)

;

Running the above program, the output is:



1

2

3

getc function

The xgetc function returns a single character from the specified FILEHANDLE, or from STDIN if none is 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 a buffered file handle.

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



read FILEHANDLE, SCALAR, LENGTH, OFFSET

read FILEHANDLE, SCALAR, LENGTH

Parameter description:

  • FILEHANDLE: file handle, used to hold a unique identifier for a file.
  • SCALAR: stores the result. If OFFSET is not specified, the data will be placed at the beginning of SCALAR. Otherwise, the data will be placed after the OFFSET bytes in SCALAR.
  • LENGTH: the length of the content read.
  • OFFSET: the offset amount.

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.

print function

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



print FILEHANDLE LIST

print LIST

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:



print "Hello World!\n";

File copy

The following example opens an existing file file1.txt, reads each of its lines, and writes them to the file file2.txt:

Example

#!/usr/bin/perl

Open a file in read-only mode

open

(

DATA1

,

"

"

)

;

Open a new file and write to it

open

(

DATA2

,

"

file2.txt

"

)

;

Copy Data

while

(

<

DATA1

)

{

print

DATA2

$_

;

}

close

(

DATA1

)

;

close

(

DATA2

)

;

File renaming

The following example renames the existing file file1.txt to file2.txt, with the specified directory under /usr/runoob/test/:



#!/usr/bin/perl



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

function renames accepts only two parameters and only renames files that already exist.

Delete a file

The following example demonstrates how to use unlink function to delete a file:

Example

#!/usr/bin/perl

unlink

(

"

/usr/runoob/test/file1.txt

"

)

;


Specify File Position

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:

tell function

The tell function is used to get the file position:

tell FILEHANDLE

tell

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.

seek function

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:



seek FILEHANDLE, POSITION, WHENCE

Parameter description:

  • FILEHANDLE: file handle, used to hold a unique identifier for a file.
  • POSITION: the number of bytes the file handle (read/write position pointer) is to be moved.
  • WHENCE: indicates the starting position where the file handle (read/write position pointer) begins to move. The values it can take are 0, 1, 2; these indicate the beginning of the file, the current position, 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

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:



$ cat file1.txt 

www.runoob.com

Example

#/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:



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

The file test operators are shown in the following table:

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,