Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: parsing CSV with TEXT::CSV

by Anonymous Monk
on Jul 22, 2009 at 13:12 UTC ( [id://782289]=note: print w/replies, xml ) Need Help??


in reply to parsing CSV with TEXT::CSV

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

Replies are listed 'Best First'.
Re^2: parsing CSV with TEXT::CSV
by GertMT (Hermit) on Jul 22, 2009 at 15:22 UTC
    This code is for me definitely worth to study in detail. It brings me a step further in my goal and learning process. Right now trying to sort out what this autodie module is all about.
    Many thanks!
    Gert
      autodie stops you from having to write
      open(...) or die; close ... or die;
      and allows you to use eval{} to trap fatal errors
      eval { open ...; open ...; 1 } or print "ERROR $@\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://782289]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-03-29 14:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found