user1495523
user1495523

Reputation: 505

Perl: print hash contents in a table

Could anyone provide me direction to print the contents of a scalable 2D hash in form of a table.

A sample output

    C1  C2  C3  C4
R1  0   1   2   -
R2  3   x   y   5
R3  4   3   -   2
R4  6   6   6   2

The contents above are available in the Hash and where there is missing data, the output is represented by '-'. The number and columns in the output are not fixed.

regards

Upvotes: 0

Views: 100

Answers (1)

mpapec
mpapec

Reputation: 50667

perl -MData::Dumper -lane'
  @c=@F, next if $. ==1;
  $k = shift @F;
  @{ $h{$k} }{@c} = @F;
  }{ print Dumper \%h;
' file

output

$VAR1 = {
      'R3' => {
                'C3' => '-',
                'C4' => '2',
                'C2' => '3',
                'C1' => '4'
              },
      'R1' => {
                'C3' => '2',
                'C4' => '-',
                'C2' => '1',
                'C1' => '0'
              },
      'R4' => {
                'C3' => '6',
                'C4' => '2',
                'C2' => '6',
                'C1' => '6'
              },
      'R2' => {
                'C3' => 'y',
                'C4' => '5',
                'C2' => 'x',
                'C1' => '3'
              }
    };

Upvotes: 1

Related Questions