CX89 Apple tree
CX89 Sailing boat
CX89 Apple tree
AC75 Apple candy
CX89 Sailing boat
#!/usr/bin/perl -- use strict; use warnings; use diagnostics; use Text::CSV; use Text::CSV_XS qw( ); #main { use autodie 2.06; open( my $fh_in, '<', 'data.txt' ); my $col_rules = [ [ [ 1 => eq => 'Apple'], [ 0 => eq => 'CX89'], [ "%s %s tree\n" => [ 0, 1 ] ], ], [ [ 1 => eq => 'Sailing'], [ 0 => eq => 'CX89'], [ "%s %s boat\n" => [ 0, 1 ] ], ], [ [ 0 => ne => 'CX89'], [ 1 => eq => 'Apple'], [ 1 => ne => 'Sailing'], [ "%s %s candy\n" => [ 0, 1 ] ], ], ]; process_rules( $col_rules, $fh_in, \*STDOUT ); } sub process_rules { my ( $rules, $in, $out ) = @_; my $csv_in = Text::CSV->new( { sep_char => ',', eol => $/ } ) or die Text::CSV->error_diag(); my $csv_out = Text::CSV->new( { eol => $/ } ) or die Text::CSV->error_diag(); while ( my $row = $csv_in->getline($in) ) { my $rulematch = 0; for my $ruleset (@$rules) { last if $rulematch; my $ruleset_match = 0; for my $rule ( @$ruleset[0 .. $#$ruleset ] ) { my ( $ix, $op, $val ) = @$rule; $ruleset_match++ if $op eq 'eq' and $val eq $row->[$ix]; $ruleset_match++ if $op eq 'ne' and $val ne $row->[$ix]; } #~ warn '$rulematch ',$rulematch; #~ warn '$ruleset_match ', $ruleset_match ; #~ warn '$#$ruleset ', $#$ruleset ; if ( $ruleset_match == $#$ruleset ) { $rulematch++; my ( $printf, $indices ) = @{ $ruleset->[-1] }; $out->printf( $printf, (@$row)[@$indices] ); } } } } __DATA__ "CX89",Apple "CX89",Sailing "CX89",Apple "AC75",Apple "CX89",Sailing

In reply to Re: parsing CSV with TEXT::CSV by Anonymous Monk
in thread parsing CSV with TEXT::CSV by GertMT

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.