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

Got a bit of a prob:

I have a simple form with a few fields directed to a text file.
One of the fields is a textfield. When this is filled in without new line (carriage return) there is no problem and the field is recorded normally. However if the user uses the carriage return to begin a new line this starts a new line in the text file.
I have tried stripping out new lines and / or carriage returns but this strips out the whole response for that field.

my $address=$query->param('address'); my $address =~ s/\n/<br>/g; my $address =~s/\r//g;
I'd be grateful for some help on this.

Replies are listed 'Best First'.
Re: How to handle new lines in textfield (CGI)
by dga (Hermit) on Mar 28, 2003 at 23:47 UTC

    One solution is to change the delimiter in your text file to something that will not be present in the input field.

    For example you could use a double linefeed to seperate records then single line feeds would not end your record. This has the obvious problem of what if the user enters a blank line. You could trim any double linefeeds out of course and this method retains the format that the user put the data into the form as a side effect.

    The problem with the current code which would be noted under use warnings; is that you are making up a new copy of address 3 times in the code.

    my $address=$query->param('address'); $address =~ s/\n/<br>/g; $address =~ s/\r//g;

    See if that makes it better. warnings would say some thing similar to: my declaration masks variable in same scope.

      Thanks very much for your input, dga. Removing the my's did the trick (why didn't I see that? Aaarrrghh!).

      I don't have warnings on this particular script because it is very large, not my own and didn't have warnings before. From the way it is written I think warnings would produce large plumes of black smoke from the back of my computer in no time:)

Re: How to handle new lines in textfield (CGI)
by perlguy (Deacon) on Mar 28, 2003 at 23:50 UTC
    Here is a possible reason, as most everything looks good to me:

    use warnings or -w switch might have told you that "my" variable $address masks earlier declaration in same scope. change:

    my $address =~ s/\n/<br>/g;
    to:
    $address =~ s/\n/<br>/g;
    and your problem *should* be solved.