http://www.perlmonks.org?node_id=969189

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

Hi Monks, Can someone please help to clarify what is the difference between below three declarations (please note the brackets):
Example 1:
my %h = { ( 1 => "j", 2 => "b", ), ( 1 => "p", 2 => "b", ), };
Example 2:
my %h = ( ( 1 => "j", 2 => "b", ), ( 1 => "p", 2 => "b", ), );
Example 3:
my %h = { { 1 => "j", 2 => "b", }, { 1 => "p", 2 => "b", }, };
Thanks in advance.

Replies are listed 'Best First'.
Re: Different Type of Hashes
by Khen1950fx (Canon) on May 07, 2012 at 09:30 UTC
    #2 is the correct way to initialize the hash with an even-sized list. #1 and #3---the brackets are in effect creating a reference which isn't what you want.

      Neither, I think, is #2!

      knoppix@Microknoppix:~$ perl -Mstrict -MData::Dumper -wE ' > my %h = ( > ( 1 => q{j}, 2 => q{b} ), > ( 1 => q{p}, 2 => q{b} ), > ); > print Data::Dumper->Dumpxs( [ \ %h ], [ qw{ *h } ] );' %h = ( '1' => 'p', '2' => 'b' ); knoppix@Microknoppix:~$

      It is not clear from the three attempts what the OP desires. If a HoH is the aim then there should be a key with a value of the inner hash reference.

      knoppix@Microknoppix:~$ perl -Mstrict -MData::Dumper -wE ' > my %h = ( > k1 => { 1 => q{j}, 2 => q{b} }, > k2 => { 1 => q{p}, 2 => q{b} }, > ); > print Data::Dumper->Dumpxs( [ \ %h ], [ qw{ *h } ] );' %h = ( 'k2' => { '1' => 'p', '2' => 'b' }, 'k1' => { '1' => 'j', '2' => 'b' } ); knoppix@Microknoppix:~$

      An AoH fits the OP's data best perhaps?

      knoppix@Microknoppix:~$ perl -Mstrict -MData::Dumper -wE ' > my @a = ( > { 1 => q{j}, 2 => q{b} }, > { 1 => q{p}, 2 => q{b} }, > ); > print Data::Dumper->Dumpxs( [ \ @a ], [ qw{ *a } ] );' @a = ( { '1' => 'j', '2' => 'b' }, { '1' => 'p', '2' => 'b' } ); knoppix@Microknoppix:~$

      It would be useful if the OP could clarify their requirement.

      Cheers,

      JohnGG

Re: Different Type of Hashes
by JavaFan (Canon) on May 07, 2012 at 18:29 UTC
    Example 1 has on the RHS of the assignment a reference to a hash, where the hash has just two elements. It's assigned to a hash, which mean the reference is stringified and acts as a key, whose value will be undef.

    Example 2 has an 8 element list on the RHS of the assignment. When turned into a hash, you end up with a 2 element hash, as the keys are repeated.

    Example 3 has a 2 element list on the RHS of the assigment, each element a reference to a hash. The second reference will survive the assignment to a hash, but the first will be stringified as the key.

    I don't know what you want; the closest I can think of is an array of hashes:

    my @h = ({1 => "j", 2 => "b"}, {1 => "p", 2 => "b"});
    Perhaps you want a two level hash, but none of the examples gives any clue as what the top level keys should be.