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

Writing to files

print with a filehandle writes text into a file.

In this page:

  1. Writing to files

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

perl
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
Common Mistakes
  1. Adding a comma after the filehandle
  2. Forgetting the newline so all lines run together
  3. 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:

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.