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
Perl has rich file handling capabilities that make it a popular language for tasks such as text processing, log file analysis, and more. In this tutorial, we'll delve into the basics of file-handling functions in Perl.
File handling operations typically involve opening a file, reading from or writing to it, and then closing it. Perl provides built-in functions for each of these steps.
open
: Used to open a file.close
: Used to close an opened file.Syntax:
open FILEHANDLE, MODE, EXPR;
FILEHANDLE
is a scalar variable that acts as a reference to the file.MODE
indicates how the file should be opened (e.g., reading, writing).EXPR
is the name of the file.Example:
open my $fh, '<', 'filename.txt' or die "Can't open file: $!"; # ... Do something with the file ... close $fh;
Here, <
is the mode for reading. The die
function will print an error message and exit the script if the file can't be opened.
<FILEHANDLE>
: In a scalar context, it reads a single line from the file. In a list context, it reads the entire file.# Reading a line my $line = <$fh>; # Reading the whole file into an array my @lines = <$fh>;
readline(FILEHANDLE)
: An explicit way to read the next line from the file.print FILEHANDLE EXPR
: Used to write to the file.open my $fh, '>', 'filename.txt' or die "Can't open file: $!"; print $fh "This is a line of text\n"; close $fh;
Here, >
is the mode for writing.
<
or read
: Read mode.>
: Write mode (creates a new file or truncates an existing one).>>
: Append mode.+<
: Read and write mode (does not truncate).+>
: Read and write mode (truncates if the file exists).Perl provides several operators to test specific attributes of files:
-e
: True if the file exists.-r
: True if the file is readable.-w
: True if the file is writable.-s
: Returns the size of the file (0 if empty).Example:
if (-e 'filename.txt') { print "The file exists.\n"; }
To read the entire content of a file into a scalar:
{ local $/; # Enables localized slurp mode open my $fh, '<', 'filename.txt'; my $content = <$fh>; close $fh; }
A common pattern in Perl is to iterate over each line in a file:
open my $fh, '<', 'filename.txt' or die "Can't open file: $!"; while (my $line = <$fh>) { chomp $line; # Removes newline character # ... Process each line ... } close $fh;
opendir
, readdir
, and closedir
allow you to work with directory contents.opendir my $dir, '/path/to/directory' or die "Can't open directory: $!"; my @files = readdir $dir; closedir $dir;
File handling is a crucial aspect of many Perl scripts. This tutorial provided an overview of essential file-handling functions. Whether you're reading logs, writing reports, or processing text files, these functions and techniques will be invaluable in your Perl programming endeavors.
Opening and closing files in Perl:
open
and close
.my $file_path = "example.txt"; # Opening a file for reading open my $file_handle, '<', $file_path or die "Could not open file: $!"; # File operations go here... # Closing the file close $file_handle or die "Could not close file: $!";
Reading from files in Perl:
while
loop.my $file_path = "example.txt"; open my $file_handle, '<', $file_path or die "Could not open file: $!"; # Reading lines from the file while (my $line = <$file_handle>) { chomp $line; print "Line: $line\n"; } close $file_handle or die "Could not close file: $!";
Writing to files in Perl:
print
.my $file_path = "output.txt"; open my $file_handle, '>', $file_path or die "Could not open file: $!"; # Writing to the file print $file_handle "Hello, Perl!\n"; print $file_handle "Welcome to file handling.\n"; close $file_handle or die "Could not close file: $!";
Appending to files in Perl:
>>
.my $file_path = "log.txt"; open my $file_handle, '>>', $file_path or die "Could not open file: $!"; # Appending to the file print $file_handle "New log entry.\n"; close $file_handle or die "Could not close file: $!";
Checking file existence in Perl:
-e
operator.my $file_path = "example.txt"; if (-e $file_path) { print "File exists.\n"; } else { print "File does not exist.\n"; }
File permissions and ownership in Perl:
-r
, -w
, -x
, stat
.my $file_path = "example.txt"; if (-r $file_path) { print "File is readable.\n"; } if (-w $file_path) { print "File is writable.\n"; } my ($mode, $uid, $gid) = (stat $file_path)[2, 4, 5]; print "File permissions: $mode\n";
File size and modification time in Perl:
-s
, stat
.my $file_path = "example.txt"; my $file_size = -s $file_path; print "File size: $file_size bytes\n"; my $modification_time = (stat $file_path)[9]; my $formatted_time = localtime $modification_time; print "Last modified: $formatted_time\n";
Copying and moving files in Perl:
File::Copy
.use File::Copy; my $source_file = "source.txt"; my $destination_file = "destination.txt"; copy($source_file, $destination_file) or die "Copy failed: $!"; move($source_file, "new_location/") or die "Move failed: $!";
Error handling in Perl file operations:
my $file_path = "example.txt"; open my $file_handle, '<', $file_path or die "Could not open file: $!"; # File operations go here... close $file_handle or die "Could not close file: $!";