<
home PYTHONJAVA
 

Perl file operation

Perl uses a variable called the file handle type to manipulate files.

File handles are 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, STDERR, which represent standard input, standard output, and standard error output, respectively.

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

Open function

The following code uses the open function to open the file file.txt in a read-only manner (<):

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

< means read-only.

The DATA in the code is the file handle used to read the file. The following example will open the file and output the contents of the file:

Instance

#!/usr/bin/perl open(DATA, "<file.txt") or die "file.txt file cannot be opened, $!"; while(< DATA>){ print "$_"; }

The following code opens the file file.txt by writing ( > ):

open(DATA, ">file.txt") or die "file.txt file could not be opened, $!";

> indicates the write mode.

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

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, the format is as follows:

open DATA, "+>file.txt" or die "the file.txt file could not be opened. $!";

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

open(DATA,">>file.txt") || die  "file.txt file could not be opened, $!";

>> means 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 file could not be opened, $!";< /pre>

The following table lists the different access modes:

The
ModeDescription
< or rRead-only is turned on, pointing the file pointer to the file header.
> or w write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
>> or aWrite mode is turned on, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
+< or r+Read and write mode opens, pointing the file pointer to the file header.
+> or w+Read and write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
+>> or a+Read and write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try to create it.

Sysopen function

The

sysopen functions are similar to the open function, except that they have different parameter forms.

The following example opens the file in read-write (+<filename):

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

If you need to empty the file before updating the file, it is written 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 parameter is an octal attribute value indicating the permissions after the file is created. The default is 0x666.

The following table lists the possible mode values:

ModeDescription
O_RDWRRead and write mode is turned on, pointing the file pointer to the file header.
O_RDONLYRead-only mode opens, pointing the file pointer to the file header.
O_WRONLYWrite mode is turned on, pointing the file pointer to the file header and cutting the file size to zero. If the file does not exist, try to create it.
O_CREATCreate a file
O_APPENDAdditional files
O_TRUNCTruncate the file size to zero
O_EXCL If the file exists when O_CREAT is used, an error message is returned, which can test if the file exists
O_NONBLOCK Non-blocking I/O makes our operations either successful or returns an error immediately without being blocked.

Close function

After the file is used, close the file to refresh the input and output buffers associated with the file handle. The syntax for closing the file is as follows:

close FILEHANDLE
Close

FILEHANGLE is the specified file handle and returns true if it is successfully closed.

close(DATA) || /span>die "Unable to close file";

Read and write files

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

<FILEHANDL> operator

The primary method for reading information from an open file handle is the <FILEHANDLE> operator. In a scalar context, it returns a single row from the file handle. For example:

Instance

#!/usr/bin/perl print "welookups Tutorial URL?\n"; $name = <STDIN>; print "URL:$name\n";

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

Implement the creation of the import.txt file with the following content:

$ cat import.< /span>txt
1
2
3

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

Instance

#!/usr/bin/perl open(DATA,"<import.txt") or die "Unable to open data"; @lines = <DATA>; print @lines; # output array content close(DATA);

Execute the above program, the output is:

1
2
3

getc function

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

getc FILEHANDLE
Getc

If an error occurs, or if the file handle is at the end of the file, then 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< /span>, LENGTH, OFFSET
Read FILEHANDLE, SCALAR, LENGTH

Parameter description:

  • FILEHANDLE: A file handle that holds a unique identifier for a file.
  • SCALAR: Stores the result. If no OFFSET is specified, the data will be placed at the beginning of SCALAR. Otherwise the data is placed after the OFFSET byte in SCALAR.
  • LENGTH: The length of the content read.
  • OFFSET: Offset.

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

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

print FILEHANDLE LIST
print LIST
print

Using the file handle and print function to send the results of the program to the output device (STDOUT: standard output), for example:

print "Hello World! \n";

File copy

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

Instance

#!/usr/bin/perl # Open file as read-only open(DATA1, "<file1.txt"); # Open a new file and write to it open(DATA2, ">file2.txt"); # Copy data while(< DATA1>) { print DATA2 $_; } close( DATA1 ); close( DATA2 );

File Rename

In the following example, we renamed the existing file file1.txt to file2.txt, and the specified directory is under /usr/welookups/test/:

#!/usr/bin/perl

Rename ("/usr/welookups/test/file1.txt" , "/usr/welookups/test/file2.txt" < /span>);
The

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

Delete files

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

Instance

#!/usr/bin/perl unlink ("/usr/welookups/test/file1.txt");

Specify 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:

tell function

The

tell function is used to get the file location:

tell FILEHANDLE
Tell

If FILEHANDLE is specified, this function returns the position of the file pointer, in bytes. Returns the default selected file handle if not specified.

seek function

The

seek() function reads or writes a file by moving the file read and write pointers through a file handle, reading and writing in bytes:

seek FILEHANDLE, POSITION< /span>, WHENCE

Parameter description:

file1.txt Information: is a text file, 15 bytes

The file test operators are shown in the following table:

OperatorDescription
-A The last time the file was accessed (unit: day)
-B is a binary file
-C (inode) index node modification time (unit: day)
-M Time when the file was last modified (unit: day)
-O Files are owned by real UIDs
-R Files or directories can be read by real UID/GID
-S is socket(socket)
-T is a text file
-W Files or directories can be written by real UID/GID
-X Files or directories can be executed by real UID/GID
-b is a block-special (special block) file (such as a mount disk)
-c is a character-special (special character) file (such as an I/O device)
-d is the directory
-e File or directory name exists
-f is a normal file
-g File or directory has setgid attribute
-k The file or directory has a sticky bit set
-l is a symbolic link
-o File is valid by UID
-p File is named pipe (FIFO)
-r Files can be read by a valid UID/GID
-s The file or directory exists and is not 0 (returns the number of bytes)
-t The file handle is TTY (the result of the system function isatty(); this test cannot be used for file names)
-u File or directory has setuid attribute
-w Files can be written by a valid UID/GID
-x Files can be executed by a valid UID/GID
-zThe file exists, the size is 0 (the directory is always false), that is, whether it is an empty file,





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.