Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

Use the Tie::File module. This module makes a file look like a Perl array, each array element corresponds to a line of the file.

Tie::File is very efficient; instead of rewriting the entire file, it just rewrites what is necessary to apply the modification you specify.

Example:

#!/usr/bin/perl
 
use Tie::File;
 
#-- modify all ocurrences of 'HowTo' to 'how to'
tie @lines, 'Tie::File', "readme.txt" or die "Can't read file: $!\n";
foreach ( @lines )
{
  s/HowTo/how to/g;
}
untie @lines;


If file does not exist example code creates an empty file

If that is not what you want, you can avoid this behavior like so:

#!/usr/bin/perl

use Tie::File;
use Fcntl 'O_RDWR';
# open the file if it exists, but fail if it does not exist
tie @lines, 'Tie::File', "readme.txt", mode => O_RDWR or die "Can't read file: $!\n";
#-- modify all occurrences of 'HowTo' to 'how to'
foreach ( @lines )
{
s/HowTo/how to/g;
}
untie @lines;