7

How can I declare a class variable as floating point in Moose?

My (fictional) sample below produces errors for "Real", "Number" etc ... "Str" works but defeats the purpose .. searching/Google doesn't help, since I can't hit the correct search terms...


PROBLEM.pm

package PROBLEM;
use strict;
use warnings;
use Moose;

has 'PROBLEM'=> (isa=>'real',is =>'ro',required=>'0',default=>sub {0.1;});

main.pl

use strict;
use warnings;

use PROBLEM;

my $problem=PROBLEM->new();
brian d foy
  • 129,424
  • 31
  • 207
  • 592
lexu
  • 8,766
  • 5
  • 45
  • 63

2 Answers2

8

Check out the Moose Types documentation. There is no built-in float type, just Num and its subtype Int. This makes sense, since Perl really doesn't differentiate (visibly) between floats and integers.

The best thing to do is probably to use Num as the type constraint, or write your own type that coerces the value into some form that suits your needs.

friedo
  • 65,762
  • 16
  • 114
  • 184
  • The official documentation for default types is in the Moose docs: http://search.cpan.org/dist/Moose/lib/Moose/Util/TypeConstraints.pm#Default_Type_Constraints – perigrin Sep 17 '09 at 15:11
6

You need Num type for a real number:

{
    package Problem;
    use Moose;

    has 'number' => ( 
        isa      => 'Num', 
        is       => 'ro', 
        default  => sub { 0.1 },
    );
}


my $problem = Problem->new;
say $problem->number;  # => 0.1
AndyG
  • 39,700
  • 8
  • 109
  • 143
draegtun
  • 22,441
  • 5
  • 48
  • 71