Your skill will accomplishwhat the force of many cannot PerlMonks

### Re: Counting Data in two columns?

by neniro (Priest)
 on Jun 15, 2006 at 10:32 UTC ( #555466=note: print w/replies, xml ) Need Help??

in reply to Counting Data in two columns?

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' );

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' );

my \$self = shift;
die unless @_ == 2;

my \$name = shift;
my \$person = shift;

if (exists \$self->{fruits}->{\$name}) {
my \$fruit = \$self->{fruits}->{\$name};
} else {
my \$fruit = Fruit->new;
\$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+)\$/;
}

print \$box->to_s;

__DATA__
apple  Tom
orange Tom
pear   Tom
mango  David
apple  David

Create A New User
Node Status?
node history
Node Type: note [id://555466]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2018-01-22 20:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (237 votes). Check out past polls.

Notices?