in reply to creating hash of hashes from input file
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: creating hash of hashes from input file
by chimiXchanga (Novice) on Mar 03, 2017 at 13:38 UTC |