0

Which structure is created as following in Perl?

my $self = { Name => $name, Color => $class->default_color };

If it is a hash, then is the official notation not the following ( parentheses, % instead of $):

my %self = ( Name => $name, Color => $class->default_color );
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Skip
  • 6,240
  • 11
  • 67
  • 117

3 Answers3

5

The data in { ... } is a hash ref.

The data in ( ... ) is a list, but the context makes it into a hash.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

Well, it's still a hash - but an anonymous one. And its reference is assigned to $self. The doc says:

A reference to an anonymous hash can be created using curly brackets:

$hashref = {    
  'Adam'  => 'Eve',     
  'Clyde' => 'Bonnie',
};
raina77ow
  • 103,633
  • 15
  • 192
  • 229
3

Perl doesn't have a literal representation of a hash, so we create a hash as a list of key-value pairs. The anonymous hash constructor or assignment to named hash converts the list of key-value pairs to a hash.

The top line creates a hash reference which you assign to a scalar variable:

my $self = { Name => $name, Color => $class->default_color };

The bottom line assigns a list to a named hash:

my %self = ( Name => $name, Color => $class->default_color );
brian d foy
  • 129,424
  • 31
  • 207
  • 592