snape has asked for the wisdom of the Perl Monks concerning the following question:

I was going through a snippet of code and I didn't understand the following notation (line 5 in the code below]. I am confused as how can a hash be represented as an array or is it a different form of hash of arrays or is array of hashes. The code is as follows:

my @Data; my @cols = qw(col1 col2 col3 col4); while (<STDIN>) { chomp; my %table; @table{@cols} = split /\t/; ## Explain push @Data, \%table; }

Replies are listed 'Best First'.
Re: Data Structure: HOA or AOH ??
by afoken (Chancellor) on Jan 30, 2010 at 22:27 UTC

    See hash slice -- essentially, the left-hand side @table{@cols} is a list of hash elements, the right hand side is a list of strings returned by splitting each input line at TAB characters.

    $table{'col1'} is assigned the first string contained in each input line, $table{'col2'} is assinged the second string, and so on. If there are more than four strings, only the first four are used. If there are less than four strings, the remaining hash elements are assigned the undef value.

    You could write the same code more verbosely as:

    ($table{'col1'},$table{'col2'},$table{'col3'},$table{'col4'})=split /\t/;

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: Data Structure: HOA or AOH ??
by Anonymous Monk on Jan 30, 2010 at 22:28 UTC
Re: Data Structure: HOA or AOH ??
by umasuresh (Hermit) on Jan 30, 2010 at 22:41 UTC
    @table{@cols} = split /\t/;
    The input data is stored in a array of hash hash slice with each element in the @cols as keys. The reference to the hash table is then stored in @data.
    http://www.manning.com/cross/
    free download Chapter 2 has a figure explaining just this!
    HTH
    Update:  @table{@cols} = split /\t/; is a hash slice as others have mentioned!

      The input data is stored in an array of hash

      No. Please refer to the earlier answers.

        ikegami,
        Thanks for pointing out the mistake. I am still trying to wrap my brain around a hash slice.
Re: Data Structure: HOA or AOH ??
by umasuresh (Hermit) on Feb 01, 2010 at 20:07 UTC
    I stumbled upon this very useful way of visualizing the above data structure using the Data::Dumper module. So far I had only used this for Hashes.
    When the line below is added at the very end, it prints this complex data structure!
    print Dumper(\@Data);