#!/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 = ; # 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