in reply to Making a two dimensional hash with first row and column as the keys

perldsc
use warnings; use strict; my $hdr = <DATA>; my @cols = split /\s+/, $hdr; my %hash; # pick a better name while (<DATA>) { my ($row, @vals) = split; for my $i (0 .. $#vals) { $hash{$row}{$cols[$i+1]} = $vals[$i]; } } print "$hash{aaa}{baz}\n"; __DATA__ Log foo bar baz aaa 123 456 789 bbb 987 654 321
  • Comment on Re: Making a two dimensional hash with first row and column as the keys
  • Download Code

Replies are listed 'Best First'.
Re^2: Making a two dimensional hash with first row and column as the keys
by AnomalousMonk (Archbishop) on Jul 06, 2011 at 18:38 UTC

    A slight variation on toolic's approach:

    perl -wMstrict -le "my $data = qq{Log foo bar baz \n} . qq{aaa 123 456 789 \n} . qq{bbb 987 654 321 \n} ; ;; open my $fh, '<', \$data or die qq{opening data: $!}; ;; my (undef, @dim2_names) = split /\s+/, <$fh>; print qq{ @dim2_names}; ;; my %hash_2d; while (defined(my $rec = <$fh>)) { my ($row, @vals) = split /\s+/, $rec; print qq{$row = @vals}; @{ $hash_2d{$row} }{ @dim2_names } = @vals; } ;; use Data::Dumper; print Dumper \%hash_2d; " foo bar baz aaa = 123 456 789 bbb = 987 654 321 $VAR1 = { 'bbb' => { 'bar' => '654', 'baz' => '321', 'foo' => '987' }, 'aaa' => { 'bar' => '456', 'baz' => '789', 'foo' => '123' } };
Re^2: Making a two dimensional hash with first row and column as the keys
by limzz (Novice) on Jul 06, 2011 at 14:56 UTC

    Are you a wizard? Thanks a lot, this is exactly what I needed :) I was actually closer than I thought, but my way was really wonky.