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

I am trying to get an upload of a CSV file from an upload field on a webpage. Currently the webpage is used by Mac, Windows, and Linux users. When a Mac user uploads, $/ is not set correctly so the CSV appears as a single line and gets thrown out by the system. How can I accurately figure out whether I need to update $/ to use the correct line breaks so that my CSV file gets parsed correctly.
my $file = $q->upload('event_upload'); my $start_row = $q->param('row_start'); ## Toss out lines until we hit the specified start row if ($start_row) { for (1..$start_row) { my $garbage = <$file>; } } while (my $line = <$file>) { ### Do file stuff }
Godzirra! Destroying Neo Tokyo since 1954

Replies are listed 'Best First'.
Re: Mac vs. PC line breaks
by Joost (Canon) on Aug 05, 2005 at 16:06 UTC
    # guess to set $/ to correct linebreaks # untested code. local $/ = \1000; # read first 1000 bytes local $_ = <$file>; my $newline; for my $test ("\015\012","\015","\012") { # match various newline char +s, default to unix $newline = $test; last if /$test/; } local $/ = $newline; seek $file,0,0; # rewind to start of file

    You should probably also use Text::xSV or Text::CSV_XS instead of trying to parse it yourself.

    update: qw() doesn't interpolate \015, so I fixed that

    update2: ikegami pointed out a typo. I fixed it.

      Typo: "\015\12" should be "\015\012"

      But why not replace

      my $newline; for my $test ("\015\012","\015","\012") { # Default to unix. $newline = $test; last if /$test/; }

      with

      # Default to unix. my ($newline) = /(\015\012|\015|\012)/ ? $1 : "\012";

      which simplies to

      # Default to unix. my ($newline) = /(\015\012?)/ ? $1 : "\012";
Re: Mac vs. PC line breaks
by jhourcle (Prior) on Aug 05, 2005 at 16:07 UTC

    The logic to handle this was just recently in the question alter $/ - but why?

    Of course, you'd probably want to localize the changes to $/, especially if the program persists through more than one file upload