kurotsuki
kurotsuki

Reputation: 4797

How do "{}" (braces) create a hash, and why can I store it as a scalar?

In perltoot is this code:

$rec = {
  name  => "Jason",
  age   => 23,
  peers => [ "Norbert", "Rhys", "Phineas"],
};

Is this a string or some sort of hash (I thought hashes were declared with %)?

Upvotes: 3

Views: 185

Answers (2)

leonbloy
leonbloy

Reputation: 75996

It's a reference (sort of a pointer) to a hash. And a reference (as anything that begins with '$' in Perl) is an scalar, in this case a scalar that "points" to a non-scalar value.

  @ta = (10,20,30); # array
  $tb = [10,20,30]; # reference to an array
  %tc = (name => 'John', age => 23); # hash
  $td = {name => 'John', age => 23}; # reference to a hash

  print( $ta[1] . "\n");
  print( $tb->[1] . "\n");

  print( $tc{'name'} . "\n");
  print( $td->{'name'} . "\n");

Understanding references is essential to any more than casual Perl programming. For example, you need to use references to make nested structures ( arrays of arrays, etc).

Upvotes: 12

ikegami
ikegami

Reputation: 386501

{ } creates both a hash and a reference to it, and it returns the latter.

{ a => 1, b => 2 }

is roughly equivalent to

do { my %anon = ( a => 1, b => 2 ); \%anon }

This operator is documented in perlref.

Upvotes: 6

Related Questions