in reply to Re^2: Creating CSV file
in thread Creating CSV file

Here data structure is the key. It looks like you are using three arrays in parallel to manage data records. Instead you should be using an array of records - each record being either a hash or an array as you think most appropriate. Consider:

#!/usr/bin/perl use strict; use warnings; use Text::CSV; my @ports = qw(portname portID port802); my @val1 = qw(ON ON OFF); my @val2 = qw(EX EX NEX); my @records; while (@ports) { push @records, [shift @ports, shift @val1, shift @val2]; } my $csv = Text::CSV->new ({sep_char => ';'}); for my $record (@records) { if ($csv->combine (@$record)) { print $csv->string, "\n"; } else { print "combine () failed on argument: ", $csv->error_input, "\ +n"; } }

Prints:

portname;ON;EX portID;ON;EX port802;OFF;NEX

Note that much of the rest of your program would likely benefit from using record oriented storage as illustrated rather than scattering related data across disparate arrays as indicated in your sample.

True laziness is hard work

Replies are listed 'Best First'.
Re^4: Creating CSV file
by Tux (Canon) on Aug 01, 2010 at 08:13 UTC

    Or, much more consice:

    #!/usr/bin/perl use strict; use warnings; use Text::CSV; my @ports = qw(portname portID port802); my @val1 = qw(ON ON OFF); my @val2 = qw(EX EX NEX); my $csv = Text::CSV->new ({sep_char => ';', eol => "\n", auto_diag => +1 }); for (@ports) { $csv->print (*STDOUT, [ $_, shift @val1, shift @val2 ]); }

    Enjoy, Have FUN! H.Merijn

      Concise was not the point. Adopting an appropriate data structure was. Note that the meat of my reply however boils down to:

      $csv->print (*STDOUT, $_) for @records;

      where your 'concise' equivalent was:

      for (@ports) { $csv->print (*STDOUT, [ $_, shift @val1, shift @val2 ]); }

      which after all is part of why an appropriate data structure is a 'good thing'™ ;-)

      True laziness is hard work

        Very much so. My point was more that using ->combine () plus print ..., "\n" embedded in error checking code is not as efficient and readable as a single call to the ->print () method using the correct attributes in the constructor.


        Enjoy, Have FUN! H.Merijn