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

Greetings! I'm new to the community, still trying to wrap my head around sigils, arrays, hashes etc...and I think the problem is simple enough:
Can someone tell me what's going on here? Is it a hash? The $ and {} brackets are confusing. Thanks!
my $thing = { a => $a, b => $b, };

Replies are listed 'Best First'.
Re: Is this a hash?
by toolic (Bishop) on Jun 16, 2015 at 14:29 UTC
    $thing is a scalar variable which contains a reference to a hash (defined with the curlies). See perlreftut and perldata.

    This shows a hash variable (using parentheses):

    my %thing = ( a => $a, b => $b, );
Re: Is this a hash?
by davido (Cardinal) on Jun 16, 2015 at 14:29 UTC

    $thing will contain a hash reference, or more precisely, a reference to an anonymous hash constructed by the { ... } operator, which in this usage is a hash reference constructor.

    You can refer to the hash as a reference ($thing), or as a hash (%{$thing} or %$thing), and you may refer to its individual elements by dereferencing it: $thing->{'a'}.

    This would be a named hash:

    my %thing = ( a => $a, b => $b, );

    Dave

Re: Is this a hash?
by pme (Monsignor) on Jun 16, 2015 at 14:32 UTC
    Hi nhnl,

    Welcome to the monastery!

    $thing is a hashref. You can read more about perlrefs perlref and perlreftut.

    use strict; use Data::Dumper; my $a = 5; my $b = 6; my $thing = { a => $a, b => $b, }; print Dumper($thing) . "\n";
    output is
    $VAR1 = { 'a' => 5, 'b' => 6 };
Re: Is this a hash?
by talexb (Chancellor) on Jun 16, 2015 at 18:16 UTC

    You've got a pile of answers already, but here's one more!

    Here's a hash:

    my %hash = ( a => 1, b => 2 ); print $hash{'b'}; # prints 2
    And here's a hashref, which is like the one that you had:
    my $hashref = { c => 3, d => 4 }; print $hashref->{c}; # prints 3
    As you can see, you use percent and brackets to define a hash, and dollar and braces to define a hashref.

    In addition, you can get a reference to something by putting a backslash in front of it ..

    my $ref_to_hash = \%hash; print $ref_to_hash->{'a'}; # prints 1
    References are useful when you want to pass data structures around -- it's more efficient to pass a reference (that big thing over there) rather than the structure itself.

    Alex / talexb / Toronto

    Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.