Reading Files in Perl

Our first program will demonstrate reading files in Perl. Here’s the full source code with explanations.

use strict;
use warnings;
use File::Slurp;
use IO::Seekable;

# This helper function will streamline our error checks
sub check {
    my $e = shift;
    die $e if $e;
}

# Read the entire file into memory
my $dat = read_file("/tmp/dat");
check($!);
print $dat;

# Open a file to obtain a file handle for more control
open(my $fh, '<', "/tmp/dat") or check($!);

# Read some bytes from the beginning of the file
my $b1;
my $n1 = read($fh, $b1, 5);
check($!);
printf("%d bytes: %s\n", $n1, $b1);

# Seek to a known location in the file and read from there
seek($fh, 6, SEEK_SET) or check($!);
my $b2;
my $n2 = read($fh, $b2, 2);
check($!);
printf("%d bytes @ %d: %s\n", $n2, 6, $b2);

# Seek relative to the current position
seek($fh, 4, SEEK_CUR) or check($!);

# Seek relative to the end of the file
seek($fh, -10, SEEK_END) or check($!);

# Use sysread for more robust reading
seek($fh, 6, SEEK_SET) or check($!);
my $b3;
my $n3 = sysread($fh, $b3, 2);
check($!);
printf("%d bytes @ %d: %s\n", $n3, 6, $b3);

# Rewind to the beginning of the file
seek($fh, 0, SEEK_SET) or check($!);

# Use a buffered reader for efficiency with many small reads
my $line = <$fh>;
chomp $line;
printf("5 bytes: %s\n", substr($line, 0, 5));

# Close the file when you're done
close($fh);

To run the program, first create a test file:

$ echo "hello" > /tmp/dat
$ echo "perl" >> /tmp/dat
$ perl reading-files.pl
hello
perl
5 bytes: hello
2 bytes @ 6: pe
2 bytes @ 6: pe
5 bytes: hello

This Perl script demonstrates various ways of reading files:

  1. Reading an entire file into memory using File::Slurp.
  2. Opening a file and reading a specific number of bytes.
  3. Seeking to different positions in the file using seek.
  4. Using sysread for more robust reading.
  5. Using buffered reading with the diamond operator <>.

Note that Perl’s file handling is somewhat different from other languages. It uses functions like open, seek, and read instead of methods on a file object. The seek function in Perl is similar to other languages, allowing you to move the file pointer to different positions.

The script also demonstrates error checking, which is important when working with files. In Perl, many file operations set the $! variable on error, which we check in our check function.

Next, we’ll look at writing files in Perl.