perl - Maintain order within a hash of hashes, and output as .csv -


here's code:

my %hash = (     '2564' => {                 'st_responsible' => 'mname1',                 'critical' => '',                 'last_modified_by' => 'teamname1',                 'transstatus' => '',                 'rt_res' => 'pname1'                 },     '2487' => {                 'st_responsible' => 'mname2',                 'critical' => '',                 'last_modified_by' => 'teamname2',                 'transstatus' => '',                 'rt_res' => ''                 } );  print "xnum,st_responsible,critical,last_modified_by,transstatus,rt_res\n"; foreach $x_number (sort keys %hash) {     print "$x_number";     foreach $element (keys %{$hash{$x_number}})     {         print ",$hash{$x_number}{$element}";     }     print "\n"; } 

expected output

xnum,st_responsible,critical,last_modified_by,transstatus,rt_res 2487,mname2,,teamname2,, 2564,mname1,,teamname1,,pname1 

actual output

xnum,st_responsible,critical,last_modified_by,transstatus,rt_res 2487,mname2,,,teamname2, 2564,mname1,,,teamname1,pname1 

please in letting me know how preserve order of data structure, , write csv file.

i suggest this, you'd better off doing slice, way of extracting list of values hash in particular order?

#configure field order @order = qw ( st_responsible critical last_modified_by transstatus rt_res );  #print header row  print join (",", "xnum", @order ),"\n";  #iterate rows foreach $key ( sort keys %hash ) {     #extract hash slice , join commas    print join ( ",", $key, @{$hash{$key}}{@order} ),"\n"; }  

this gives:

xnum,st_responsible,critical,last_modified_by,transstatus,rt_res 2487,mname2,,teamname2,, 2564,mname1,,teamname1,,pname1 

you can consider text::csv - i'd suggest in scenario it's overkill, best used when you've got quotes , quoted field separators worry about. (and don't).

if have deal not empty keys, missing ones, can make use of map:

my @order = qw ( st_responsible critical last_modified_by                   transstatus missing rt_res extra_field_here ); print join (",", "xnum", @order ),"\n";  foreach $key ( sort keys %hash ) {     print join ( ",", $key, map { $_ // '' } @{$hash{$key}}{@order} ),"\n"; }  

(otherwise you'll warning undef value).


Comments