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

Opening and closing files

open connects a filehandle to a file, and close disconnects it.

Opening and closing files

The three-argument open takes a filehandle, a mode and a file name; the modes are < for reading, > for writing (which truncates the file), >> for appending and +< for reading and writing. open returns false on failure and stores the reason in $!, so it is normally followed by or die. Using a lexical filehandle declared with my is the modern style, and it is closed automatically when it goes out of scope.

Note: Always check the result of open; a missing file is a normal situation, not an impossible one.

Example: Opening and closing files

perl
use strict;
use warnings;

my $file = "demo_open.txt";
open(my $out, '>', $file) or die "Cannot open $file: $!";
print $out "created by Perl\n";
close($out) or die "Cannot close $file: $!";

open(my $in, '<', $file) or die "Cannot open $file: $!";
my $line = <$in>;
close($in);
print "read back: $line";

if (open(my $missing, '<', "no_such_file.txt")) {
    print "unexpectedly opened\n";
} else {
    print "open failed: $!\n";
}
unlink $file;

# Output:
# read back: created by Perl
# open failed: No such file or directory
Common Mistakes
  1. Not checking whether open succeeded
  2. Using > when you meant >> and erasing the file
  3. Using the old two-argument form of open with a variable file name
Chapter Summary
  • open(my $fh, MODE, FILE) opens a file
  • < reads, > writes, >> appends
  • Check failures with or die and $!
  • close releases the handle
🔒

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.