Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^6: Textfile to csv with a small twist

by jZed (Prior)
on Aug 25, 2005 at 21:17 UTC ( [id://486727]=note: print w/replies, xml ) Need Help??


in reply to Re^5: Textfile to csv with a small twist
in thread Textfile to csv with a small twist

You say you want this
H1,T1.1 CRLF T1.2 crlf,H2,T2.1 CRLF T2.2 CRLF
How will you ever retrieve the data from that? If instead you have this:
H1,"T1.1 CRLF T1.2 CRLF"
H2,"T2.1 CRLF T2.2 CRLF"
You will then be able to retrieve the text for any heading, for example if you print out the text for H2, it will look like this:
   T2.1
   T2.2
Is that what you want? If so, here's how I would do it:
#!/usr/bin/perl -w use strict; use IO::Scalar; # not needed if input and output are from files use Text::CSV_XS; my $csv = Text::CSV_XS->new( {binary=>1} ); my @input_data = <DATA>; # turn the input data into a CSV string with records and fields # my $csv_str = text_to_csv( @input_data ); # as a test, turn the CSV string back into a text string # my $output_data = csv_to_text( $csv_str ); # check that the text string created from the CSV is the same # as the original # print "ok!\n" if $output_data eq join '', @input_data; sub text_to_csv { my (@new_row,$new_text,$output_csv,$heading); for my $line (@_) { if ($line =~ /^(\w+:)$/) { $heading = $1; if (@new_row) { $output_csv .= make_row(@new_row,$new_text); } @new_row = ($heading); $new_text = ''; } else { $new_text .= $line; } } $output_csv .= make_row(@new_row,$new_text); } sub csv_to_text { my($input_str)=@_; my $output_str = ''; my $fh = IO::Scalar->new(\$input_str); while (my $cols = $csv->getline($fh)) { last unless @$cols; $output_str .= sprintf "%s\n%s", @$cols; } return $output_str; } sub make_row { my $success = $csv->combine(@_); die "Coulnd't parse '@_'\n" unless $success; return $csv->string . "\n"; } __DATA__ H1: T1.1 T1.2 H2: T2.1 T2.2
Note that only the text_to_csv() sub is needed to do what you asked, the other subs are there as tests and illustrations.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-25 14:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found