🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of bkhl

bkhl's solution

to Word Count in the Perl 5 Track

Published at Sep 20 2019 · 0 comments
Instructions
Test suite
Solution

Given a phrase, count the occurrences of each word in that phrase.

For example for the input "olly olly in come free"

olly: 2
in: 1
come: 1
free: 1

Source

This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

word_count.t

#!/usr/bin/env perl
use strict;
use warnings;
use open ':std', ':encoding(utf8)';
use utf8;

use Test2::Bundle::More;
use FindBin qw($Bin);
use lib $Bin, "$Bin/local/lib/perl5";

my $module = 'Phrase';

my @cases = (

# input                                       expected output                  title
  [ 'word', { word => 1 }, 'one word' ],
  [ 'one of each', { one => 1, of => 1, each => 1 }, 'one of each' ],
  [ 'one fish two fish red fish blue fish',
    { one => 1, fish => 4, two => 1, red => 1, blue => 1 },
    'multiple occurences'
  ],
  [ 'car : carpet as java : javascript!!&@$%^&',
    { car => 1, carpet => 1, as => 1, java => 1, javascript => 1 },
    'ignore punctuation'
  ],
  [ 'testing, 1, 2 testing',
    { testing => 2, 1 => 1, 2 => 1 },
    'include numbers'
  ],
  [ 'go Go GO', { go => 3 }, 'normalize case' ],
);

plan 3 + @cases;

ok -e "$Bin/$module.pm", "missing $module.pm"
  or BAIL_OUT(
  "You need to create a module called $module.pm with a function called word_count() that gets one parameter: the text in which to count the words."
  );

eval "use $module";
ok !$@, "Cannot load $module.pm"
  or BAIL_OUT("Does $module.pm compile?  Does it end with 1; ?");

can_ok( $module, 'word_count' )
  or BAIL_OUT("Missing package Phrase; or missing sub word_count()");

my $sub = $module . '::word_count';

foreach my $c (@cases) {
  no strict 'refs';
  is_deeply $sub->( $c->[0] ), $c->[1], $c->[2];
}
package Phrase;

use strict;
use warnings FATAL => 'all';

use Exporter qw(import);
our @EXPORT_OK = qw(word_count);

sub word_count() {
    my ($phrase) = @_;

    my %result;

    $result{lc $_}++ foreach ($phrase =~ /(\w+)/g); 

    return \%result;
}

1;

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?