File Handling in Perl: Reading, Writing, and Manipulating Files

April 14, 2024

File handling is an essential aspect of programming. In this post, we will learn how to work with files in Perl, including reading from and writing to files, as well as manipulating file content using Perl’s file handling capabilities.

Opening and Closing Files

In Perl, file handling involves opening a file, performing operations such as reading or writing, and then closing the file. The open function is used to open a file for reading or writing, and the close function is used to close the file once the operations are complete.


open(my $file_handle, '<', file.txt') or die 'Cannot open file: $!';
# Perform file operations

close($file_handle);

Reading from Files

To read from a file in Perl, we can use the open function to open the file and then use the << operator to read the content line by line.


open(my $file_handle, '<', 'file.txt') or die 'Cannot open file: $!';
while (my $line = <$file_handle>) {
    # Process each line
}
close($file_handle);

Writing to Files

Writing to files in Perl involves opening the file for writing using the open function and then using the > operator to write content to the file.


open(my $file_handle, '>', 'output.txt') or die 'Cannot open file: $!';
print $file_handle 'Hello, World!';
close($file_handle);

Manipulating File Content

Perl provides various functions and operators for manipulating file content, such as seek to move the file pointer, truncate to resize a file, and rename to rename a file.

With these file handling capabilities, Perl allows developers to efficiently read, write, and manipulate file content, making it a powerful language for file operations.