Wednesday, November 01, 2006

Perl : use Tie::File

With Tie::File module you can read all lines of a file in an array. Updating array elements updates the corresponding lines in the file. This is more efficient than reading the whole file, doing replacements and writing it back.

Following code snippet is an example

use Tie::File;

tie @line_array, 'Tie::File', 'file' or die "Can not tie file:$!";
for (@line_array) {
        s/pattern/replacement/g;
        ### or do anything that you wish to
        ### updating elements of array will update corresponding lines in the tied file
        ### pushing an element will add a line
}
untie @line_array;

Tie::File is very efficient for updating large files.

No comments: