Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some hashes initialized using curly braces, and some with parentheses?

Tags:

I'm looking at the following code demonstrating nested hashes:

my %HoH = (
    flintstones => {
        husband   => "fred",
        pal       => "barney",
    },
    jetsons => {
        husband   => "george",
        wife      => "jane",
        "his boy" => "elroy",  # Key quotes needed.
    },
    simpsons => {
        husband   => "homer",
        wife      => "marge",
        kid       => "bart",
    },
);

Why is it that the upper-most hash (starting line 1) is initialized using parentheses, whereas the sub-hashes are initialized using curly braces?

Coming from a python background I must say Perl is quite odd :).

like image 239
Adam S Avatar asked Aug 07 '12 05:08

Adam S


2 Answers

The essential difference (....) is used to create a hash. {....} is used to create a hash reference

my %hash  = ( a => 1 , b => 2 ) ;
my $hash_ref  = { a => 1 , b => 2 } ;

In a bit more detail - {....} makes an anonymous hash and returns a reference to it wich is asigned to the scalar $hash_ref

edited to give a bit more detail

like image 24
justintime Avatar answered Oct 13 '22 01:10

justintime


Coming from a Perl background I find Perl quite odd, too.

Use parentheses to initialize a hash (or an array). A hash is a map between a set of strings and a set of scalar values.

%foo = ( "key1", "value1",  "key2", "value2", ... );   #  % means hash
%foo = ( key1 => "value1",  key2 => "value2", ... );   # same thing

Braces are used to define a hash reference. All references are scalar values.

$foo = { key1 => "value1", key2 => "value2", ... };    #  $ means scalar

Hashes are not scalar values. Since the values in a hash must be scalars, it is therefore not possible to use a hash as a value of another hash.

%bar = ( key3 => %foo );     # doesn't mean what you think it means

But we can use hash references as values of another hash, because hash references are scalars.

$foo = { key1 => "value1", key2 => "value2" };
%bar = ( key3 => $foo );
%baz = ( key4 => { key5 => "value5", key6 => "value6" } );

And that is why you see parentheses surrounding a list of lists with braces.

like image 100
mob Avatar answered Oct 13 '22 02:10

mob