file-io intermediate

How to use File::Slurp to read files in Perl?

Question

How to use File::Slurp to read files in Perl?

The File::Slurp module provides a neat way to read and write entire files in Perl with minimal code. It automatically handles opening, reading, and closing files, returning file content either as a scalar (whole file) or a list (lines) depending on context.

In the previous example, the code tried to read a file named example.txt which didn’t exist, causing an error. When demonstrating file operations in a sandbox environment without filesystem access, it’s best to simulate file content or avoid actual file reading. Since the question focuses on usage, here's a safe example that reads data from a temporary in-memory filehandle using the File::Slurp interface style, but adapted to work entirely in-memory by using a string as the file content (mimicking reading a file).

Key Points about File::Slurp Usage

  • read_file reads files in scalar or list context:
    • Scalar context returns the entire file content as a string.
    • List context returns the file as a list of lines (with trailing newlines).
  • It dies on failure by default, so files must exist or handle exceptions.
  • For binary or UTF-8 safe reading, options like binmode => ':raw' can be used.
  • Without filesystem access, simulate reading using data embedded in your script.

Example: Mimicking read_file Reading from a String

This example bypasses actual file reading and demonstrates the context-sensitive behavior of read_file-like calls by manually emulating their outputs with hardcoded data.

use strict;
use warnings;

# Simulate file content as a single string
my $file_content = "First line\nSecond line\nThird line\n";

# Emulate read_file in scalar context (whole file)
my $content_scalar = $file_content;
print "File content as a single string:\n";
print $content_scalar, "\n";

# Emulate read_file in list context (array of lines)
my @content_lines = split /\n/, $file_content;
# Add newlines back since read_file includes them by default
$_ .= "\n" for @content_lines;

print "File content as lines:\n";
print for @content_lines;

This script demonstrates the TMTOWTDI principle: the same "read_file" logic returns different data depending on context, but here using plain Perl variables because actual file I/O is disallowed. In real usage with File::Slurp, you would call:

use File::Slurp;

my $scalar = read_file("example.txt");      # scalar context
my @lines = read_file("example.txt");       # list context

but these require accessible files on disk. When testing or sandboxed, this emulation helps understand the behavior clearly.

Common Pitfalls

  • Trying to read a non-existent file leads to a fatal error unless error mode is set.
  • Confusing scalar vs list context changes what data read_file returns.
  • Assuming newlines are automatically removed; read_file preserves them when returning a list of lines.
  • Using File::Slurp for very large files can consume lots of memory.
  • For UTF-8 files, explicit binmode => ":utf8" may be needed (Perl 5.10+).

Summary

File::Slurp simplifies file reading by automatically handling filehandles and returning content in the desired scalar or list context. For sandboxed or constrained environments without access to real files, simulating file content can illustrate the concept clearly without runtime errors. When working with actual files, ensure they exist and consider encoding and error handling options.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 9ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
File content as a single string:
First line
Second line
Third line

File content as lines:
First line
Second line
Third line
STDERR
(empty)

Was this helpful?

Related Questions