Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
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' ); 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


Comment on Re: Counting Data in two columns?
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://555466]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (11)
As of 2014-09-19 11:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (135 votes), past polls