apocrates has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've created the below script (yes, I'm new to this) and I'm trying to just add an entry to the .txt file. Only problem is it's just putting one entry into the file! please tell me how I've screwed this up. Thanks!
#!/usr/bin/perl -w $filename = shift || "Fav_mov.txt"; open (FILE, ">$filename") or die "can't open $filename: $!\n"; print "Your favorite movie: "; $line = <>; @movies = (); push @movies, "$line"; foreach $movie (@movies) { print "$movie\n" } print "Thank you!\n"; close(FILE);

Replies are listed 'Best First'.
(jeffa) Re: Newbie Script
by jeffa (Bishop) on Nov 21, 2001 at 21:45 UTC
    First off you will want to open your file with >> not >. >> appends to the file, > writes over the file:
    open (FILE, ">>$filename") or die "trying";
    Secondly, if you want to actually write to that file handle, you need to specify the file handle when you print:
    print FILE "$movie\n";
    Also, you might want to wrap the whole grabbing of user input around a while loop - otherwise your @movies array is totally unecessary.

    Lastly, but very important - don't quote bare variables:

    push @movies, "$line"; # bad habit to get into push @movies, $line; # much better, what if $line was a reference?

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
Re: Newbie Script
by andye (Curate) on Nov 21, 2001 at 21:44 UTC
    open (FILE, ">$filename") to overwrite, open (FILE, ">>$filename") to append.

    perlfunc:open

    hth,
    andy.

Re: Newbie Script
by hopes (Friar) on Nov 21, 2001 at 21:48 UTC
    Try this:
    #!/usr/bin/perl -w use strict; my $filename = shift || "Fav_mov.txt"; open (FILE, ">>$filename") or die "can't open $filename: $!\n"; print "Your favorite movie: "; my $line = <>; print FILE "$line"; print "Thank you!\n"; close(FILE);
    Comments:
    use strict and warnings, is safer.
    To append to any file, use ">>$filename"
    If you want to write to a filehandle, you have to specify it; if you don't do it, you'll be writting to STDOUT (or select it).
    Remember that if you select FILE, you should specify STDOUT to print "Thank you!\n".
    Hope this helps


    Hopes
    $_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s, $_^=q,$\^-]!,,print
      Thank you for all your help! :)