Writing to files
print with a filehandle writes text into a file.
In this page:
Writing to files
Put the filehandle right after print, printf or say, with no comma after it. Opening with > creates the file or empties an existing one, while >> adds to the end. You can also print a whole list, and printf gives formatted lines.
Note:
Use a block such as print {$fh} ... when the filehandle is stored in a complex expression, such as a hash element.
Example: Writing to files
use strict;
use warnings;
my $file = "demo_write.txt";
open(my $fh, '>', $file) or die "Cannot write $file: $!";
print $fh "first line\n";
printf $fh "%-6s %3d\n", "apples", 12;
my @more = ("second\n", "third\n");
print $fh @more;
close $fh;
open($fh, '>>', $file) or die "Cannot append $file: $!";
print $fh "appended line\n";
close $fh;
print "file size: ", -s $file, " bytes\n";
open($fh, '<', $file) or die;
print while <$fh>;
close $fh;
unlink $file;
# Output:
# file size: 49 bytes
# first line
# apples 12
# second
# third
# appended line
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Adding a comma after the filehandle
- Forgetting the newline so all lines run together
- Reading from a handle that was opened only for writing
Chapter Summary
- print $fh LIST writes to a file
- No comma after the filehandle
- > truncates and >> appends
- printf works with filehandles too
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: