Home > Software design >  How do I get it to stop removing what was previously in the text file?
How do I get it to stop removing what was previously in the text file?

Time:10-08

Have a file with names, display the people in the file, then ask the person if they want to sign up, agree with Y, prompt them for their name, then add their name to the end of the file (if they say y) append the name to the end of the file using Perl.

This is the assignment, and this code below is mostly functional. However, when you input a name, it will remove all the other names that may have been in the file previously.

my $file = "name.txt";

# Use the open() function to open the file.
unless(open FILE, $file) {
    # Die with error message
    # if we can't open it.
    die "\nUnable to open $file\n";
}

while(my $line = <FILE>) {
    print $line;
}

open (fh, ">", "name.txt");
print "Do you want to sign up? \n";

$choice = <STDIN>;
$y = "yes\n";
if ($choice eq $y) {
  print "Enter your name\n";
}

$a = <>;

# Writing to the file
print fh $a;

close(fh) or "Couldn't close the file";

CodePudding user response:

The way you open the file, you open it to write (>), not append(>>).

Change

open (fh, ">", "name.txt");

to include >> and not >:

open (fh, ">>", "name.txt");

Also, Perl Appending, appends text to the bottom of the file. If you would want to append to the start of the file then check out this answer.

CodePudding user response:

The main problem is that you used the wrong MODE when you opened the file the second time. From open:

If MODE is >, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is >>, the file is opened for appending, again being created if necessary.

The reason your file was overwritten was that you opened it with >, which clobbers your existing file. As the document states, you need to use >> to append lines to the end of your file.

Another problem is that, even when the user enters no instead of yes, the code prompts for a name anyway, then writes the name to the file. Unless the user inputs yes, you don't want to write to the file, so all that code belongs inside the if block.

Here is a more conventional way to write your code:

use warnings;
use strict;

my $file = 'name.txt';

open my $fh, '<', $file or die "\nUnable to open $file: $!\n";
while (my $line = <$fh>) {
    print $line;
}
close $fh;

print "Do you want to sign up? \n";
my $choice = <STDIN>;
my $y = "yes\n";
if ($choice eq $y) {
    print "Enter your name\n";
    my $name = <>;
    open $fh, '>>', $file;
    print $fh $name;
    close $fh;
}

It is important to use strict and warnings. There are benefits to using a lexical filehandle ($fh) instead of bare filehandles (FILE). It is good practice to explicitly use the mode for open, even with opening for input (<).

  •  Tags:  
  • perl
  • Related