code_junkie

How do you create objects in Perl?

Nov 10th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.59 KB | None | 0 0
  1. package Point;
  2. use Moose; # automatically turns on strict and warnings
  3.  
  4. has 'x' => (is => 'rw', isa => 'Int');
  5. has 'y' => (is => 'rw', isa => 'Int');
  6.  
  7. sub clear {
  8. my $self = shift;
  9. $self->x(0);
  10. $self->y(0);
  11. }
  12.  
  13. my $p = Point->new({x=>10 , y=>20}); # Free constructor
  14. $p->x(15); # Free setter
  15. print $p->x(); # Free getter
  16. $p->clear();
  17. $p->x(15.5); # FAILS! Free type check.
  18.  
  19. package Person;
  20. use Moose;
  21. has age => ( isa => Int, is => 'rw');
  22. has name => ( isa => Str, is => 'rw');
  23. 1;
  24.  
  25. my $person = Person->new();
  26. $person->age(34);
  27. $person->name('Mike');
  28. print $person->name, "n";
Add Comment
Please, Sign In to add comment