Except the newline doesn't appear after the last line from each field.
For example, if TEXTAREA 1 contains:
A
B
C
and TEXTAREA 2 contains:
1
2
3
then my text file looks like this:
A
B
C 1
2
3
Here's my HTML code:
<html>
<form method=post action=test.cgi>
<textarea name=field1></textarea>
<textarea name=field2></textarea>
<input type=submit>
</form>
</html>
And my Perl code:
#!/usr/bin/perl
use CGI qw(:standard);
for $loop (1..2) {
$field = param('field'.$loop);
@items = split("\n",$field);
for $item (@items) { $output .= $item."\n"; }
}
open(FILE,'>test.txt');
print FILE $output;
close(FILE);
Interestingly, if I print the output to the screen (Content-type:text/plain), it appears properly.
My text editor is TextWrangler. I chose "Show Invisibles" and it shows a red upside-down question mark between "C" and "1", and after "3".
Please don't tell me to just avoid splitting the input into individual lines. I really need to split the input, since in my final script I'll be performing some operations on each line individually.
Who understands newline issues?
then my text file looks like this:
In what, TextWrangler, which is showing you the \n's are there?
It's likely something system specific, and those differences are showing themselves in cross-platform examination. I say this because
if I print the output to the screen (Content-type:text/plain), it appears properly
... prints the output to the screen from your server, where it's still OK, but when you view it in a text editor, it's not. Unix-based servers have different end of line characters than Windows/Mac. Some things you can try:
- put the \n at the beginning of the lines instead
- experiment with \r or \r\n instead
- May or may not have any relevance, but be sure your editor can read Unix formatted files correctly
- Since you know your \n's are showing up where you expect them to be, and your task doesn't involve any reason for the files to be used off the server, forge onward with the rest of your task, as you don't really have a problem (maybe?)
So I looked a little harder, and I found the problem was with this line:
@items = split("\n",$field);
The input was actually coming in delimited with "\r\n", so setting the split pattern to that, fixed the problem.
But that raises another question: Does field input reliably come in with "\r\n" at the end of each line from any browser/OS combo? Or is sometimes it just "\r", and sometimes just "\n"?
The regex I often use for locating line endings is the carriage return first, making it optional \r?\n but if you are just looking to remove any and all of them the regex provided is going to meet your needs, as has already been suggested, confirmed and reconfirmed.