Home > Net >  Perl Moose, How to initialize a instance attribute that is Hash
Perl Moose, How to initialize a instance attribute that is Hash

Time:07-01

What I am tring to do is the following:

I am writing a perl Moose Class and I want ot have a class attribute that is an Hash and is initialized to default values upon building.

My attempt:

has sweep_prop_configuration => (
    is=>'rw',
    isa => 'Hash',
    reader => 'sweep_prop_configuration',
    writer => '_sweep_prop_configuration',
    builder => '_build_sweep_prop_configuration',
    predicate => 'has_sweep_prop_configuration',
);

sub _build_sweep_prop_configuration {
  my $self = shift;
  my %hash;
  $hash{point_number}=0;
  $hash{number_of_sweep}=0;
  $hash{backwards}=-1;
  $hash{at_end}=-1;
  $hash{at_end_val}=0;
  $hash{save_all}=-1;
  return %hash;
}

I am new to Moose and perl in general, excuse me if I missed something in the documentation.

CodePudding user response:

Moose doesn't define Hash as a type (see Moose::Manual::Types).

It defines HashRef, though. In order to use it, change the builder's last line to

return \%hash

and change the type constraint to

isa => 'HashRef',

It still defines an instance attribute, not a class attribute. To define class attributes, use MooseX::ClassAttribute.

  • Related