#!perl use strict; use Data::Dumper; my $actid; my $key; my $last; my $colno = 0; my @order = (); my %cols = (); my %data = (); #my $infile = 'data.txt'; #open IN,'<',$infile or die "$!"; while (){ #or IN chomp; next unless /\S/; # skip blank lines # continuation line if (! /:/){ $data{$actid}{$key} .= $_; next; } ($key,my $value)= split ':',$_,2; # create unique phone column if ($key eq 'Phone'){ $key = $last.' '.$key } $last = $key; if ( $key eq 'Activity' ){ $actid = $value; push @order,$actid; } $cols{$key} = ++$colno unless exists $cols{$key}; $data{$actid}{$key} = $value; } # close IN; print Dumper \%data; print Dumper \%cols; # output use Text::CSV; my $csv = Text::CSV->new ( { binary => 1 , eol => "\n", } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); # col headings my @header = sort { $cols{$a} <=> $cols{$b} } keys %cols; print Dumper \@header; $csv->column_names(@header); # ouput records open my $fh, '>', "new.csv" or die "new.csv: $!"; $csv->print($fh,\@header); for my $actid (@order){ $csv->print_hr($fh, $data{$actid}); } close $fh or die "new.csv: $!"; __DATA__ Activity:C2012-0109 Type:COMBO ..