← Back to Perl Course | Chapter 5: File I/O | Lesson 4 of 7

Reading a whole file

In list context <$fh> returns every line, and setting a special variable can read the file in one piece.

In this page:

  1. Reading a whole file

Reading a whole file

In list context the readline operator returns all remaining lines as a list, which is handy for small files. To get the whole file as a single string, set the input record separator $/ to undef inside a local block, which is called slurping. chomp with a list removes the newline from every element.

Note: Use local $/; inside a small block so the change does not affect the rest of the program.

Example: Reading a whole file

perl
use strict;
use warnings;

my $file = "demo_slurp.txt";
open(my $w, '>', $file) or die "Cannot write: $!";
print $w "one\ntwo\nthree\n";
close $w;

open(my $fh, '<', $file) or die "Cannot read: $!";
my @lines = <$fh>;
close $fh;
chomp @lines;
print "lines: ", scalar(@lines), " -> @lines\n";

my $content = do {
    local $/;
    open(my $in, '<', $file) or die "Cannot read: $!";
    <$in>;
};
print "characters: ", length($content), "\n";
my $newlines = () = $content =~ /\n/g;
print "newlines: $newlines\n";
unlink $file;

# Output:
# lines: 3 -> one two three
# characters: 14
# newlines: 3
Common Mistakes
  1. Slurping very large files into memory
  2. Setting $/ to undef and forgetting to restore it
  3. Forgetting that each element read in list context still ends with a newline
Chapter Summary
  • List context returns all lines
  • local $/ = undef slurps a file
  • chomp works on a whole array
  • Only slurp small files
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.