How to create hash hashes in Perl?

Based on my current understanding of Perl hashes, I expect this code to print "hello world". Instead, it does not print anything.

%a=(); %b=(); $b{str} = "hello"; $a{1}=%b; $b=(); $b{str} = "world"; $a{2}=%b; print "$a{1}{str} $a{2}{str}"; 

I assume the hash is like an array, so why can't I make a hash containing another?

+7
perl perl-data-structures hash
source share
5 answers
  • You should always use "use strict"; in your program.

  • Use links and anonymous hashes.

 use strict;use warnings; my %a; my %b; $b{str} = "hello"; $a{1}={%b}; %b=(); $b{str} = "world"; $a{2}={%b}; print "$a{1}{str} $a{2}{str}"; 

code>

{%b} creates a link to a copy of the %b hash. You need to copy here because you emptied it later.

+6
source share

Hash hashes are complex to get right for the first time. In this case

 $a{1} = { %b }; ... $a{2} = { %b }; 

takes you where you want to go.

See perldoc perllol for details on two-dimensional data structures in Perl.

+6
source share

Short answer: hash keys can only be associated with a scalar, not a hash. To do what you want, you need to use links.

Instead of intercepting (heh) how to create multi-level data structures, I suggest you read perlreftut. perlref is more perfect, but at first it is a bit overwhelming.

+4
source share

Mike, Alexander is the correct answer.

Also advice. If you just study hashes, Perl has a module called Data :: Dumper that can pretty print your data structures for you, which is very convenient if you want to check what values ​​your data structures have.

 use Data::Dumper; print Dumper(\%a); 

when you print this it shows

 $VAR1 = { '1' => { 'str' => 'hello' }, '2' => { 'str' => 'world' } }; 
+2
source share

Perl loves smoothing your data structures. This is often a good thing ... for example, (@options, "another option", "yet another") ends up as one list.

If you really want to have one structure inside another, the internal structure should be a reference. For example:

 %a{1} = { %b }; 

Brackets mean a hash that you populate with values ​​from% b, and come back as a link, not a direct hash.

You can also say

 $a{1} = \%b; 

but this makes the changes to% b also the change to $ a {1}.

+1
source share

All Articles