zoffixznet / Mojo-CSV

Non-nonsense CSV operations in Perl 5 with Mojo flavour
0 stars 1 forks source link

Reading from STDIN #7

Open geira opened 1 week ago

geira commented 1 week ago

How can I get Mojo::CSV to parse STDIN? Have tried several methods, e.g.:

Mojo::CSV->new->in('-'); # coercion for "in" failed: Failed to open CSV file (-)

Mojo::CSV->new->in(STDIN); # Bareword "STDIN" not allowed while "strict subs" in use

my $input_fh = *STDIN{IO};
my $csv = Mojo::CSV->new->in($input_fh); # Can't handle IO data

my $input_fh = \*STDIN;
my $csv = Mojo::CSV->new->in($input_fh); # no error, just fails to read data

Seems much simpler in Text::CSV, where you can just use csv( in => *STDIN ).

zoffixznet commented 6 days ago

Maybe there's an issue with your CSV data. Using \*STDIN works:

$ echo -e "1,2,3\n4,5,6" | perl -MMojo::CSV -MData::Dumper -wlE 'say Dumper [ Mojo::CSV->new->slurp( \*STDIN ) ]'
$VAR1 = [
          bless( [
                   [
                     '1',
                     '2',
                     '3'
                   ],
                   [
                     '4',
                     '5',
                     '6'
                   ]
                 ], 'Mojo::Collection' )
        ];

$ echo -e "1,2,3\n4,5,6" | perl -MMojo::CSV -MData::Dumper -wlE 'say Dumper [ Mojo::CSV->new( in => \*STDIN )->row ]'
$VAR1 = [
          [
            '1',
            '2',
            '3'
          ]
        ];

$
geira commented 6 days ago

Indeed it was, turned out it was semicolon-separated and not comma-separated. However Text::CSV managed to parse the file just fine into one column, instead of doing nothing:

my $csv = csv( in => *STDIN, sep_char => ";", encoding => ":encoding(UTF-8)", ) or die Text::CSV->error_diag;
zoffixznet commented 5 days ago

Yeah, Mojo::CSV originally was quick and dirty common-case thing. Possibly the "_obj" attribute could be changed to something that can be publicly set, so people could provide their more configured Text::CSV object (or perhaps a way to pass extra options to Text::CSV object used under the hood): https://github.com/zoffixznet/Mojo-CSV/blob/d95a8217a63def22058109b8063933cfa10047d0/lib/Mojo/CSV.pm#L25-L27