If you like OOP(erl):
#!/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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|