in reply to Appending to a file.
Before I say anything else, I'll warn you against that little ($$) thing. That's called a "prototype" and it doesn't do what you think it does. In most situations, prototypes are unhelpful.
Anyway, your problem is that you read each line of the file into memory, do something with it, and then don't write it anywhere. What you want to do is be opening both an input filehandle and an output filehandle, and writing the line to the output filehandle when you're done with it. Something like this:
sub addSecondary { my ($email, $secondary) = @_; open my $input, '<', 'registration.dat'; open my $output, '>', 'registration.tmp'; while (<$input>) { chomp; my $line = $_; if ($line =~ /$email/) { $line =~ s/nodata/$secondary/gi; } print $output "$line\n"; } close $input; close $output; unlink 'registration.dat'; rename 'registration.tmp' 'registration.dat'; }
(Note to pedants: for cross-platform compatibility unlink 'filename' is better written as 1 while unlink 'filename' because some operating systems allows multiple versions of the same file to be stored.)
There are various modules that make line-by-line file editing easier. Corion mentioned Tie::File. I happen to be a fan of File::Slurp. Here's an example using that...
use File::Slurp qw(:edit); sub addSecondary { my ($email, $secondary) = @_; edit_file_lines { s/nodata/$secondary/gi if /$email/ } 'registration.dat'; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Appending to a file.
by xavierarmadillo (Initiate) on May 07, 2012 at 16:50 UTC | |
by MidLifeXis (Monsignor) on May 07, 2012 at 17:24 UTC | |
by tobyink (Canon) on May 07, 2012 at 18:58 UTC | |
by AnomalousMonk (Archbishop) on May 07, 2012 at 19:34 UTC |