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'; }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

In reply to Re: Appending to a file. by tobyink
in thread Appending to a file. by xavierarmadillo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.