YouTip LogoYouTip

Perl Files

Perl File Operations \\n\\n

Perl uses a type of variable called a file handle to operate on files.

\\n\\n

Reading from or writing to a file requires the use of a file handle.

\\n\\n

File handle is the name of an I/O connection.

\\n\\n

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

\\n\\n

In Perl, you can open a file using the following methods:

\\n\\n
open FILEHANDLE, EXPR\\nopen FILEHANDLE\\nsysopen FILEHANDLE, FILENAME, MODE, PERMS\\nsysopen FILEHANDLE, FILENAME, MODE\\n
\\n\\n

Parameter description:

\\n\\n
    \\n
  • FILEHANDLE: The file handle, used to store a unique identifier for a file.
  • \\n
  • EXPR: An expression consisting of the filename and the file access mode.
  • \\n
  • MODE: The file access mode.
  • \\n
  • PERMS: Permission bits.
  • \\n
\\n\\n
\\n\\n

open Function

\\n\\n

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

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

< indicates read-only mode.

\\n\\n

In the code, DATA is the file handle used to read the file. The following example will open the file and output its contents:

\\n\\n

Example

\\n\\n
#!/usr/bin/perl\\n\\nopen(DATA, "<file.txt") or die "file.txt file cannot open, $!";\\nwhile(<DATA>){\\n    print "$_";\\n}\\n
\\n\\n

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

\\n\\n
open(DATA, ">file.txt") or die "file.txt file cannot open, $!";\\n
\\n\\n

> indicates write mode.

\\n\\n

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

\\n\\n
open(DATA, "+<file.txt") or die "file.txt file cannot open, $!";\\n
\\n\\n

This method will not delete the original content of the file. To delete it, use the following format:

\\n\\n
open DATA, "+>file.txt" or die "file.txt file cannot open, $!";\\n
\\n\\n

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

\\n\\n
open(DATA, ">>file.txt") || die "file.txt file cannot open, $!";\\n
\\n\\n

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

\\n\\n
open(DATA, "+>>file.txt") || die "file.txt file cannot open, $!";\\n
\\n\\n

The following table lists the different access modes:

\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
ModeDescription
< or rOpen for reading only, with the file pointer positioned at the beginning of the file.
> or wOpen for writing only, with the file pointer positioned at the beginning of the file and the file size truncated to zero. If the file does not exist, it attempts to create it.
>> or aOpen for writing only, with the file pointer positioned at the end of the file. If the file does not exist, it attempts 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, with the file pointer positioned at the beginning of the file and the file size truncated to zero. If the file does not exist, it attempts 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, it attempts to create it.
\\n\\n
\\n\\n

Sysopen Function

\\n\\n

The sysopen function is similar to the open function, but their parameter formats are different.

\\n\\n

The following example opens a file for reading and writing (+<filename):

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

If you need to clear the file before updating it, the syntax is as follows:

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

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

\\n\\n

The PERMS parameter is an octal attribute value representing the permissions of the file after creation, with a default of 0x666.

\\n\\n

The following table lists possible mode values:

\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
ModeDescription
O_RDWROpen for reading and writing, with the file pointer positioned at the beginning of the file.
O_RDONLYOpen for reading only, with the file pointer positioned at the beginning of the file.
O_WRONLYOpen for writing only, with the file pointer positioned at the beginning of the file and the file size truncated to zero. If the file does not exist, it attempts to create it.
O_CREATCreate a file.
O_APPENDAppend to the file.
O_TRUNCTruncate the file size to zero.
O_EXCLIf the file exists when using O_CREAT, it returns an error message. It can be used to test if a file exists.
O_NONBLOCKNon-blocking I/O ensures that our operation either succeeds or immediately returns an error without being blocked.
\\n\\n
\\n\\n

Close Function

\\n\\n

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

\\n\\n
close FILEHANDLE\\nclose\\n
\\n\\n

FILEHANDLE is the specified file handle. If closed successfully, it returns true.

\\n\\n
close(DATA) || die "cannot close file";\\n
\\n\\n
\\n\\n

Reading and Writing Files

\\n\\n

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

\\n\\n

<FILEHANDLE> Operator

\\n\\n

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

\\n\\n

Example

\\n\\n
#!/usr/bin/perl\\n\\nprint "URL?n";\\n$name = <STDIN>;\\nprint "URL:$namen";\\n
\\n\\n

After executing the above program, it will display the following information. After we enter the URL, the print statement will output:

\\n\\n

Image 1

\\n\\n

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

\\n\\n

First, create an import.txt file with the following content:

\\n\\n
$ cat import.txt\\n123\\n
\\n\\n

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

\\n\\n

Example

\\n\\n
#!/usr/bin/perl\\n\\nopen(DATA, "<import.txt") or die "cannot open data";\\n@lines = <DATA>;\\nprint @lines;\\nclose(DATA);\\n
\\n\\n

After executing the above program, the output is:

\\n\\n
123\\n
\\n\\n

getc Function

\\n\\n

The getc function returns a single character from the specified FILEHANDLE. If not specified, it returns from STDIN:

\\n\\n
getc FILEHANDLE\\ngetc\\n
\\n\\n

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

\\n\\n
\\n\\n

read Function

\\n\\n

The read function is used to read information from a buffered file handle.

\\n\\n

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

\\n\\n
read FILEHANDLE, SCALAR, LENGTH, OFFSET\\nread FILEHANDLE, SCALAR, LENGTH\\n
\\n\\n

Parameter description:

\\n\\n
    \\n
  • FILEHANDLE: The file handle, used to store a unique identifier for a file.
  • \\n
  • SCALAR: Stores the result. If OFFSET is not specified, the data will be placed at the beginning of SCALAR. Otherwise, the data is placed OFFSET bytes into SCALAR.
  • \\n
  • LENGTH: The length of the content to read.
  • \\n
  • OFFSET: The offset.
  • \\n
\\n\\n

If the read is successful, it returns the number of bytes read. If at the end of the file, it returns 0. If an error occurs, it returns undef.

\\n\\n

print Function

\\n\\n

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

\\n\\n
print FILEHANDLE LIST\\nprint LIST\\nprint\\n
\\n\\n

Using a file handle and the print function, you can send the results of program execution to an output device (STDOUT: standard output). For example:

\\n\\n
print "Hello World!n";\\n
\\n\\n

File Copy

\\n\\n

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

\\n\\n

Example

\\n\\n
#!/usr/bin/perl\\n\\nopen(DATA1, "<file1.txt");\\nopen(DATA2, ">file2.txt");\\n\\nwhile(<DATA1>){\\n    print DATA2 $_;\\n}\\n\\nclose(DATA1);\\nclose(DATA2);\\n
\\n\\n

File Rename

\\n\\n

In the following example, we rename the existing file file1.txt to file2.txt. The specified directory is /usr/tutorial/test/:

\\n\\n
#!/usr/bin/perl\\n\\nrename ("/usr/tutorial/test/file1.txt", "/usr/tutorial/test/file2.txt" );\\n
\\n\\n

The rename function only accepts two parameters and only renames existing files.

\\n\\n

Delete File

\\n\\n

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

\\n\\n

Example

\\n\\n
#!/usr/bin/perl\\n\\nunlink("/usr/tutorial/test/file1.txt");\\n
\\n\\n
\\n\\n

Specifying File Position

\\n\\n

You can use the tell function to get the current position of the file, and the seek function to specify a position within the file:

\\n\\n

tell Function

\\n\\n

The tell function is used to get the file position:

\\n\\n
tell FILEHANDLE\\ntell\\n
\\n\\n

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

\\n\\n

seek Function

\\n\\n

The seek() function reads or writes a file by moving the file read/write pointer via the file handle, reading and writing in bytes:

\\n\\n
seek FILEHANDLE, POSITION, WHENCE\\n
\\n\\n

Parameter description:

\\n\\n
    \\n
  • FILEHANDLE: The file handle, used to store a unique identifier for a file.
  • \\n
  • POSITION: The number of bytes the file handle (read/write position pointer) is to move.
  • \\n
  • WHENCE: The starting position from which the file handle (read/write position pointer) begins to move. The possible values are 0, 1, and 2, representing the beginning of the file, the current position, and the end of the file, respectively.
  • \\n
\\n\\n

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

\\n\\n
seek DATA, 256, 0;\\n
\\n\\n
\\n\\n

File Information

\\n\\n

Perl's file operations can also test whether a file exists, is readable or writable, etc.

\\n\\n

We can first create a file1.txt file with the following content:

\\n\\n
$ cat file1.txt\\nwww.\\n
\\n\\n

Example

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

After executing the above program, the output is:

\\n\\n
file1.txt Info: is a text file, 15 bytes\\n
\\n\\n

The file test operators are listed in the following table:

\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
OperatorDescription
-ATime since last access (in days)
-BIs it a binary file?
-CInode modification time (in days)
-MTime since last modification (in days)
-OFile is owned by real UID
-RFile or directory is readable by real UID/GID
-SIs it a socket?
-TIs it a text file?
-WFile or directory is writable by real UID/GID
-XFile or directory is executable by real UID/GID
-bIs it a block-special file (e.g., mounted disk)?
-cIs it a character-special file (e.g., I/O device)?
-dIs it a directory?
-eDoes the file or directory name exist?
-fIs it a regular file?
-gDoes the file or directory have the setgid attribute?
-kDoes the file or directory have the sticky bit set?
-lIs it a symbolic link?
-oFile is owned by effective UID
-pIs the file a named pipe (FIFO)?
-rFile is readable by effective UID/GID
-sFile or directory exists and is not zero (returns byte count)
-tIs the file handle a TTY (return value of system function isatty(); this test cannot be used on filenames)?
-uDoes the file or directory have the setuid attribute?
-wFile is writable by effective UID/GID
-xFile is executable by effective UID/GID
-zFile exists and size is zero (always false for directories), i.e., is it an empty file?
← Perl Error HandlingPerl References β†’