Perl tutorial - Appending to files

In this episode of the Perl tutorial we are going to see how to append to files using Perl.

In the previous episode we learned how to write to files. That's good when we are creating a file from scratch.

Calling


  open(my $fh, '>', 'report.txt');

will delete the content of the file if it had any.

There are cases when you would rather keep the original file and only add lines to the end.

The most prominent case is when you are writing a log file.

In that case use two greater-than signs as in this example:


  open(my $fh, '>>', 'report.txt');

Calling this function will open the file for appending. that means the file will remain intact and anything your print() or say() to it will be added to the end.

The full example is this:


  use strict;
  use warnings;
  use 5.010;

  my $filename = 'report.txt';
  open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
  say $fh "My first report generated by perl";
  close $fh;
  say 'done';

If you run this script several times, you will see that the file is growing. Every run of the script will add another row to the file.

Exercise

Write a script that would ask the user for his/her name and append it to a report.txt file.

Run the script several times to see it is really working.


Perl tutorial and video course

For further articles see the Beginner Perl Maven tutorial book and video course.


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
blog comments powered by Disqus
Online courses:


Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed