Broad Network


Writing and Editing Text File Content in Perl

Handling Files and Directories in Perl Part 2

Perl Course

Foreword: In this part of the series, I explain how to print text into a text file and how to edit a text file.

By: Chrysanthus Date Published: 27 Aug 2015

Introduction

This is part 2 of my series, Handling Files and Directories in Perl. In this part of the series, I explain how to print text into a text file and how to edit a text file. You should have read the previous part of the series, as this is a continuation. For simplicity, the file is assumed to be in the working directory, which is the directory that has the perl script. I give you some of the knowledge directly and for the rest, I answer frequently asked questions in an optimum way. If you are not using ActivePerl, then begin every code sample with something like, #!/usr/bin/perl .

Perl frequently asked questions are answered. By answering frequently asked questions, that is a phase in teaching Perl in an optimized way. By answering FAQ in an optimized way, that is producing optimized Perl coding.

Opening a File for Printing
To open a file for writing (to disk) you would type something like:

        open(fHandle, ">", "input.txt") or die "cannot open input.txt : $!";

Note that the open function has 3 arguments, with > as a separate argument. > means open file to write content; erase any previous content that the file might have had; if file did not exist in disk, create one.

When you have finished writing to the file, you close it, with a statement like:

    close fHandle;

Here, fHandle is the same handle you used in opening the file. The close function returns true on success and false on failure.

The print Function
The syntaxes for the print function are:

    print FILEHANDLE LIST

    print FILEHANDLE
    print LIST

print means write. FILEHANDLE is the filehandle of the file to which writing has to be made. What is actually written is a list of strings, which may or may not be in parentheses. With Perl functions, parentheses are optional for the list of arguments. Of course, the arguments in the list are separated by commas (you may have only one argument).

If FILEHANDLE is omitted, printing is done to the last selected output handle, and this may be STDOUT (the console). If LIST is omitted, the scalar value of $_ is printed to the currently selected handle (which may be the console as you have seen in the previous series).  

The following code prints three lines into a file. If the file did not exist, it is created. If the file existed, all its content is erased and replaced with the list of strings. This action on the file is as a result of > .

use strict;

    open(fHandle, ">", "output.txt") or die "cannot open output.txt : $!";
    print fHandle "I love you.\n", "He loves you.\n", "She loves him.\n", "This happens.\n";
    close fHandle;

Try the code and you will notice that nothing is printed to the console, since the handle is a filehandle. You will also notice that the file output.txt has been created, having 4 lines, where each line is a string value in the list. If a value is a number, it will also be printed. If a value is a number, it does not need to be in quotes.

The second main argument to the print function is a list. So, you can print an array. The following code prints an array to a file.

use strict;

    my @arr = ("child", "boy", "girl", "man", "woman");
    open(fHandle, ">", "output.txt") or die "cannot open output.txt : $!";
    print fHandle @arr;
    close fHandle;

Now this code prints all the array values in one line, i.e.

    childboygirlmanwoman

To separate the values, you need to modify the array content as follows:

    my @arr = ("child, ", "boy, ", "girl, ", "man, ", "woman");

and you get,

    child, boy, girl, man, woman

Well, this is good, but the values are still in one line. To have each value in a line, you have to modify the array content as follows:

    my @arr = ("child \n", "boy \n", "girl \n", "man \n", "woman");

The file content would be:

child
boy
girl
man
woman

Now, when the string arguments are too many and each string ends with a \n, and the strings are being prepared as they are written (to disk), then you should print in more than one line, as follows:

use strict;

    open(fHandle, ">", "output.txt") or die "cannot open output.txt : $!";
    print fHandle "I love you.\n";
    print fHandle "He loves you.\n";
    print fHandle "She loves him.\n";
    print fHandle "This happens.\n";
    close fHandle;

Editing or Modifying a Text File
The simplest way to edit a file, is to copy the lines of the file into an array; edit the cells of the array; copy the contents of the array back to the file; and then un-define the array to free memory. In the following code, the file has 4 lines. The second and third lines are modified:

use strict;

    open(fHandle, "<", "myFile.txt") or die "cannot open file : $!";
    my @lines = <fHandle>;
    $lines[1] = "He hates you.\n";
    $lines[2] = "She hates him.\n";
    close fHandle;

    open(fHandle, ">", "myFile.txt") or die "cannot open file : $!";
    for (my $i=0; $i<@lines; ++$i)
        {        
            print fHandle $lines[$i];
        }
    close fHandle;

    undef @lines;

To prepend lines to the file, unshift lines to the array. To append lines to the file, append lines to the array. To delete a line in the file, replace the line in the array with an empty string, "". It is assumed that each line in the array has its terminating \n (an empty string does not have \n). After everything, do not forget to un-define the array to free memory.

You should actually replace the above for-loop with the following, which is faster:

    my $i = 1; #counter
    foreach (@lines)
        {
            print fHandle $_;
        }
    continue
        {
            ++$i;
        }

That is it for this part of the series.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message