in reply to removing carriage returns in text area (cgi)
If it were me, i would use Text::CSV_XS to parse the data. Don't do this by hand (don't believe me? wait until a user submits good,bad,"good,""bad""",good -- and yes, that's valid CSV). Fetch what the user submitted via CGI::param() and split on one or zero carriage returns (\r) followed by one newline (\n). For each of those "rows" use said CPAN module to parse and then see if the number of elements returned is less than some sentinal value (i'll use 4 - handling the error of more than 4 is left as an excercise). From there, it's up to you how to display errors, the way i do it is just a suggestion. Normally i post these example scripts using 100% CGI.pm ... but since errors are being reported back to the user, i prefer to use HTML::Template.
Here is the code for you to dissect. Download any modules that you don't have and run the code. I think you'll like the resuts (and if they don't meet your requirements, feel free the change them ;)).
#!/usr/bin/perl -T use strict; use warnings; use Data::Dumper; use Text::CSV_XS; use HTML::Template; use CGI qw(header param textarea); my (@parsed,@error); my $tmpl = HTML::Template->new(filehandle => \*DATA); $tmpl->param(textarea => textarea('csv',undef,8,30)); my $i = 1; if (param('go')) { my $csv = Text::CSV_XS->new; for (split(/\r?\n/, param('csv'))) { if ($csv->parse($_)) { my @field = $csv->fields; if (@field < 4) { my $missing = 4 - @field; push @error, {line=>$i, error=>"$missing fields missing"}; push @parsed, undef; } else { push @parsed, [$csv->fields]; } } else { push @error, {line=>$i, error=>$csv->error_input}; push @parsed, undef; } $i += 1; } $tmpl->param(dump => Dumper(\@parsed), errors => \@error); } print header,$tmpl->output; __DATA__ <html> <head> <title>CSV Parser</title> </head> <body> <form method="post"> Enter CSV (foo,bar,baz,qux):<br/> <tmpl_var textarea> <input type="submit" name="go" value="go" /> </form> <tmpl_if errors> errors found:<br/> <tmpl_loop errors> line <tmpl_var line>: <font color="red"><tmpl_var error></font><br/> </tmpl_loop> <tmpl_else> no errors </tmpl_if> <p> Here is what i was able to parse:<br/> <pre><tmpl_var dump></pre> </p> </body> </html>
jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
|
|---|