I like this, but I would implement this with a small difference:

sub Zoo::factory {
  my ($self, $class, @args)=@_;

  my $obj="Zoo::Animal::$class"->new(@args);
  $self->{count}->{$class}++;

  return $obj;
}

my $zoo=Zoo->new();
my $camel=$zoo->factory("Camel");


I would implement this difference so I could use $zoo->{zbr} for something else, and would be easier to find the counts to every specie in the $Zoo, 'cause every key in the %{$zoo->{count}} would be a diferent specie.

The other way I think I could implement was without a factory method, but with a adquire method, with some changes:

#Zoo.pm file
sub new {
  ...
  $self->{animals}=[];
  ...
}

sub adquire {
  my $self=shift;
  push @{$self->{animals}}, @_;
}

sub count {
  my $self=shift;
  my %count=();
  for my $anim (@{$self->{animals}}) {
    $count{$anim->specie()}++;
  }
  return %count;
}

#Zoo/Animal.pm
...
sub specie {
  return "unknow specie";
}
...

#Zoo/Animal/Camel.pm
...
sub specie {
  return "cameloid Dromedarius"
}

# Main
my $zoo=Zoo->new();
$zoo->adquire(Zoo::Animal::Camel->new(), Zoo::Animal::Camel->new());
%count=$zoo->count();



If you prefer you could yet implement the count as an hash, and increment it in the adquire Zoo method, like this:

sub adquire {
  my $self=shift;
  for my $anim (@_) {
    $self->{count}->{$anim->specie()}++;
    push @{$self->{animals}}, $anim;
  }
}




In reply to Re: Re: Creating Common Constructor by themage
in thread Creating Common Constructor by DeadPoet

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.