fork download
  1. #!/usr/bin/perl
  2. my @pets = (
  3. new Dog(name => "ぽち"),
  4. new Cat(name => "たま", sleep => 1)
  5. );
  6.  
  7. foreach my $pet (@pets) {
  8. $pet->play();
  9. }
  10.  
  11.  
  12. package Animal;
  13. use strict;
  14. use warnings;
  15.  
  16. sub new {
  17. my ($class, %args) = @_;
  18. my $self = {
  19. name => $args{name},
  20. };
  21.  
  22. bless $self, $class;
  23. return $self;
  24. }
  25.  
  26. sub play {
  27. my $self = shift;
  28. }
  29.  
  30.  
  31. package Dog;
  32. use base qw( Animal );
  33.  
  34. sub new {
  35. my ($class, %args) = @_;
  36. my $self = Animal->new(%args);
  37. return bless $self, $class;
  38. }
  39.  
  40. sub play {
  41. my $self = shift;
  42. print "わんわん!" . $self->{name} . "だよ\n";
  43. }
  44.  
  45.  
  46. package Cat;
  47. use base qw( Animal );
  48.  
  49. sub new {
  50. my ($class, %args) = @_;
  51. my $self = Animal->new(%args);
  52. $self->{sleep} = $args{sleep};
  53. return bless $self, $class;
  54. }
  55.  
  56. sub play {
  57. my $self = shift;
  58. print "にゃあ!" . $self->{name} . "だよ\n";
  59. if($self->{sleep} == 1) {
  60. print "...でも寝る\n";
  61. }
  62. }
  63.  
Success #stdin #stdout 0.01s 5496KB
stdin
Standard input is empty
stdout
わんわん!ぽちだよ
にゃあ!たまだよ
...でも寝る