develooper Front page | perl.beginners | Postings from March 2008

Re: how to replace @ inside of { }

Thread Previous | Thread Next
From:
Rob Dixon
Date:
March 24, 2008 17:38
Subject:
Re: how to replace @ inside of { }
Richard Lee wrote:
 >
> Gunnar Hjalmarsson wrote:
>>
>> C:\home>type test.pl
>> use Data::Dumper;
>> my %HoA = (
>>     something  => [ qw/val1 val2 val3 and so forth/ ],
>>     something2 => [ qw/vala valb valc and so forth/ ],
>>     something3 => [ qw/valZ valZ1 valZ2 so forth/ ],
>> );
>> my %HoH;
>> while ( <DATA> ) {
>>     /^(\S+)/;
>>     @{ $HoH{$1} }{ @{ $HoA{$1} } } = split;
>> }
>> print Dumper \%HoH;
>>
>> __DATA__
>> something3 one two three etc
>> something2 two three and so on
>> something one two three four five
>>
>> C:\home>perl test.pl
>> $VAR1 = {
>>           'something3' => {
>>                             'so' => 'three',
>>                             'valZ2' => 'two',
>>                             'forth' => 'etc',
>>                             'valZ1' => 'one',
>>                             'valZ' => 'something3'
>>                           },
>>           'something2' => {
>>                             'so' => 'so',
>>                             'valb' => 'two',
>>                             'forth' => 'on',
>>                             'valc' => 'three',
>>                             'vala' => 'something2',
>>                             'and' => 'and'
>>                           },
>>           'something' => {
>>                            'so' => 'four',
>>                            'forth' => 'five',
>>                            'val2' => 'one',
>>                            'val1' => 'something',
>>                            'val3' => 'two',
>>                            'and' => 'three'
>>                          }
>>         };
>>
>> C:\home>
>>
> Hey, this works perfectly, thanks.
> 
> I just need to understand more on this
> 
> @{ $HoH{$1} }{ @{ $HoA{$1} } } = split;
> 
> This is really spinning my heads in all direction trying to see if I can 
> truly understand them instead of just using it.

Yes, it's not the most transparent line of code is it. The while loop is
equivalent to:

while ( <DATA> ) {
   my @values = split;
   my $key = $values[0];
   my $labels = $HoA{$key};
   my %map;
   @map{@$labels} = @values;
   $HoH{$key} = \%map;
}

And IMO it's better written like that. Does that help?

Rob



Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About