Assuming the Activity code is unique within the data, and you want to preserve the column order and the record order try this ;

#!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 (<DATA>){ #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 ..

Update : ++GotToBTru for duplicate phone columns

poj

In reply to Re: creating hash of hashes from input file by poj
in thread creating hash of hashes from input file by chimiXchanga

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.