Daniel Dees Daniel Dees - 2 months ago 6
Perl Question

How to write multiple lines to a file from user input (Perl)

I am trying to do a simple perl program that takes user input and writes it to a file. However I want to be able to have multiple lines in the file instead of the entire user input being on one line (for example the users types \n so move to next line in file)

Here is my current code

sub addContentToFile {

my ($self) = @_;
open(my $fh, '>>', $self->{path}) or die "Could not open file: " .$self->{path};
print "File is open for writing...\n";

#my $input = $self->{content};
my $input = <STDIN>;

print $fh $input;

print "Added : " .$input
."To File: " .$self->{path}
."\n";

close $fh;
print "\nFile Closed.\n";
}

Answer

You have this line in your code:

my $input = <STDIN>;

That means "read from STDIN up to and including the next newline character and return that data". So, by definition, $input can only ever contain a single line of input.

There are a couple of different approaches you can take here.

1/ Put the code in a while loop.

while (<STDIN>) {
  print $fh $_;

  print "Added  : " . $_
       ."To File: " . $self->{path} 
       ."\n";
}

But how does that loop end? The user would need to enter the "end of file" character - Ctrl-D.

2/ Change $/. Strictly, <...> doesn't read to the next newline character. It reads to the next occurrence of whatever is currently in $/ (the input record separator). The default value for $/ is a newline, but we can change that.

{
  local $/ = "\n\n"; # Localised change in a naked block

  my $input = <STDIN>;

  print $fh $input;

  print "Added  : " . $input
       ."To File: " . $self->{path} 
       ."\n";
}

Here we've changed $/ to two newline characters. So we will continue to accept user input until they enter two consecutive newlines.

Either of these will work, but they both make things harder for the user to use - as they need to know a special way to end their input.

Comments