Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

moose

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.

like image 223
Indiano Avatar asked Oct 28 '25 09:10

Indiano


1 Answers

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.

like image 108
choroba Avatar answered Oct 31 '25 09:10

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!