note
neniro
If you like OOP(erl):
<code>
#!/usr/bin/perl
use strict;
use warnings;
package Fruit;
use Moose;
has 'count' => ( is => 'rw' );
has 'person' => ( isa => 'ArrayRef', is => 'rw' );
sub add_person {
my $self = shift;
my $person = shift;
unless (grep {$_ eq $person} @{$self->{person}}) {
push @{$self->{person}}, $person;
}
}
sub inc {
my $self = shift;
$self->{count}++;
}
sub sum {
my $self = shift;
my $sum = $self->count;
$sum = $sum == 1 ? $sum . ' TIME ' : $sum . ' TIMES ';
return $sum;
}
sub persons {
my $self = shift;
my $people = '';
my @people = @{$self->person};
for (0..$#people) {
$people .= $_ != $#people ?
uc ($people[$_]) . ' and ' :
uc ($people[$_]);
}
return $people;
}
package FruitBox;
use Moose;
has 'fruits' => ( isa => 'HashRef', is => 'rw' );
sub add {
my $self = shift;
die unless @_ == 2;
my $name = shift;
my $person = shift;
if (exists $self->{fruits}->{$name}) {
my $fruit = $self->{fruits}->{$name};
$fruit->add_person($person) and $fruit->inc;
} else {
my $fruit = Fruit->new;
$fruit->add_person($person) and $fruit->inc;
$self->{fruits}->{$name} = $fruit;
}
}
sub to_s {
my $self = shift;
my $text = '';
for my $fruit (sort keys %{$self->{fruits}}) {
my $f = $self->{fruits}->{$fruit};
$text .= uc ($fruit) . ' appears ' . $f->sum .
'associated with ' . $f->persons . "\n";
}
return $text;
}
package main;
my $box = new FruitBox;
while (<DATA>) {
warn $_ and next unless /^(\w+)\s+(\w+)$/;
$box->add($1, $2);
}
print $box->to_s;
__DATA__
apple Tom
orange Tom
pear Tom
mango David
apple David
</code>
555383
555383