Perl Tutorial
Fundamentals
Input and Output
Control Flow
Arrays and Lists
Hash
Scalars
Strings
Object Oriented Programming in Perl
Subroutines
Regular Expressions
File Handling
Context Sensitivity
CGI Programming
Misc
File handling is a crucial aspect of most programming tasks, and Perl provides robust support for it. This tutorial will guide you through basic file handling operations in Perl, including opening, reading, writing, and closing files.
The open
function is used to open a file. It takes in a file handle (a symbolic reference to the file) and the filename, along with an optional mode:
open(my $fh, '<', 'file.txt') or die "Could not open file.txt: $!";
In this example, $fh
is the file handle. The mode '<
' specifies that the file is opened for reading. The die
function is used to terminate the script if the file can't be opened, printing an error message with $!
, which contains the error.
Common Modes:
'<
': Read mode'>'
: Write mode (creates or truncates the file)'>>'
: Append mode (creates or appends to the file)'<+'
: Read/Write modeOnce a file is opened for reading, you can use various methods to read from it:
Read Line-by-Line:
while (my $line = <$fh>) { print $line; }
Read the Entire File into an Array:
my @lines = <$fh>;
Read the Entire File into a Scalar:
my $content = do { local $/; <$fh> };
If you've opened a file in write or append mode, you can use the print
function to write to it:
open(my $fh, '>', 'output.txt') or die "Could not open output.txt: $!"; print $fh "This is a line.\nAnother line.\n"; close($fh);
After performing the required operations, you should close the file using the close
function:
close($fh);
Perl offers a variety of file tests to check attributes of files:
-e
: Checks if the file exists-r
: Checks if the file is readable-w
: Checks if the file is writable-s
: Returns the size of the file (or undef
if the file doesn't exist)Example:
if (-e 'file.txt') { print "file.txt exists.\n"; }
Changing the Working Directory:
chdir '/path/to/directory' or die "Cannot change directory: $!";
Listing Directory Contents:
opendir(my $dh, '/path/to/directory') or die "Cannot open directory: $!"; my @files = readdir $dh; closedir $dh;
Always check the return value of open
, close
, and other file operations. The variable $!
can be used to get the error message:
open(my $fh, '<', 'file.txt') or die "Could not open file.txt: $!";
File handling is straightforward in Perl, with concise syntax for common operations. Always ensure you handle errors appropriately and close files when done. This tutorial covered the basics, but Perl offers many more functionalities related to file and directory operations, making it a powerful tool for various file processing tasks.
Reading and writing files in Perl:
# Reading from a file open my $read_fh, '<', 'input.txt' or die "Cannot open input.txt: $!"; my $content = <$read_fh>; close $read_fh; # Writing to a file open my $write_fh, '>', 'output.txt' or die "Cannot open output.txt: $!"; print $write_fh "Hello, World!\n"; close $write_fh;
Perl open function examples:
open
function is used to open a file and associate a filehandle with it. It takes three arguments: the filehandle, the mode (read, write, append, etc.), and the file name.# Opening a file for reading open my $read_fh, '<', 'input.txt' or die "Cannot open input.txt: $!"; # Opening a file for writing open my $write_fh, '>', 'output.txt' or die "Cannot open output.txt: $!"; # Opening a file for appending open my $append_fh, '>>', 'log.txt' or die "Cannot open log.txt: $!";
File operations in Perl:
# Reading from a file open my $read_fh, '<', 'input.txt' or die "Cannot open input.txt: $!"; my $content = <$read_fh>; close $read_fh; # Writing to a file open my $write_fh, '>', 'output.txt' or die "Cannot open output.txt: $!"; print $write_fh "Hello, World!\n"; close $write_fh;
Working with text files in Perl:
<
mode is used for reading, and >
mode is used for writing.# Reading from a text file open my $read_fh, '<', 'textfile.txt' or die "Cannot open textfile.txt: $!"; my $content = <$read_fh>; close $read_fh; # Writing to a text file open my $write_fh, '>', 'output.txt' or die "Cannot open output.txt: $!"; print $write_fh "Hello, Text File!\n"; close $write_fh;
Binary file handling in Perl:
binmode
function to enable binary mode. This is essential for working with non-text files, such as images or executables.# Reading from a binary file open my $read_fh, '<:raw', 'binaryfile.bin' or die "Cannot open binaryfile.bin: $!"; my $content = do { local $/; <$read_fh> }; close $read_fh; # Writing to a binary file open my $write_fh, '>:raw', 'output.bin' or die "Cannot open output.bin: $!"; print $write_fh $binary_data; close $write_fh;
Perl filehandle usage:
open
function and used for reading from or writing to files.# Opening a filehandle open my $fh, '<', 'file.txt' or die "Cannot open file.txt: $!"; # Reading from the filehandle my $content = <$fh>; # Writing to the filehandle print $fh "Hello, Filehandle!\n"; # Closing the filehandle close $fh;
Appending to a file in Perl:
>>
mode is used in the open
function.# Appending to a file open my $append_fh, '>>', 'log.txt' or die "Cannot open log.txt: $!"; print $append_fh "New log entry\n"; close $append_fh;
Perl file manipulation examples:
# Reading from a file open my $read_fh, '<', 'input.txt' or die "Cannot open input.txt: $!"; my $content = <$read_fh>; close $read_fh; # Writing to a file open my $write_fh, '>', 'output.txt' or die "Cannot open output.txt: $!"; print $write_fh "Hello, World!\n"; close $write_fh; # Appending to a file open my $append_fh, '>>', 'log.txt' or die "Cannot open log.txt: $!"; print $append_fh "New log entry\n"; close $append_fh;