Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Textfile to csv with a small twist

by pbeckingham (Parson)
on Aug 25, 2005 at 18:22 UTC ( #486679=note: print w/ replies, xml ) Need Help??


in reply to Textfile to csv with a small twist

#! /usr/bin/perl use strict; use warnings; my %data; my @columns; my $current; my $line; while (<DATA>) { chomp; $line = $_; if ($line =~ /:$/) { push @columns, $line; $current = $line; $data{$current} = (); } else { push @{$data{$current}}, $line; } } print join (",", @columns), "\n"; my $count = @{$data{$columns[0]}}; for my $i (0 .. $count - 1) { for my $c (0 .. $#columns) { print $data{$columns[$c]}[$i]; print "," if $c < $#columns; } print "\n"; } __DATA__ heading1: text1 text2 text3 heading2: text1 text2 text3
Output is:
heading1:,heading2: text1,text1 text2,text2



pbeckingham - typist, perishable vertebrate.


Comment on Re: Textfile to csv with a small twist
Select or Download Code
Re^2: Textfile to csv with a small twist
by jZed (Prior) on Aug 25, 2005 at 18:35 UTC
    Except that the OP specified he/she wants the newlines as part of the data. So instead of trying to hand roll your CSV generator, use Text::CSV_XS or another CSV parsing module that's capable of recognizing and handling embedded newlines, embedded quotes, and other features hand-rolled CSV parsing usually miss.

      But it doesn't do any CSV parsing - it just reads lines. What exactly would you do with a "CSV parsing module that's capable of recognizing and handling embedded newlines, embedded quotes, and other features hand-rolled CSV parsing usually miss"? There are only text lines to read, and only CSV lines to produce. I was just illustrating a method of reading data and transposing it for output.



      pbeckingham - typist, perishable vertebrate.
        Your code has this:
        print $data{$columns[$c]}[$i]; print "," if $c < $#columns;
        That attempts to construct a CSV record by merely putting commas between fields. If there is anything in the field (for example the newlines the OP requested), then you will not end up with a valid CSV file. Text::CSV_XS has the combine() method that will properly create records by not only inserting commas, but also, when called for quoting and escaping the field data. Other CSV modules like Text::xSV have similar methods to not only parse CSV correctly, but to produce it correctly.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2014-12-22 05:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls