Opening and closing files
open connects a filehandle to a file, and close disconnects it.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Not checking whether open succeeded
- Using > when you meant >> and erasing the file
- 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: