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

alexwebgr's solution

to Two Fer in the Perl 5 Track

Published at Mar 04 2021 · 0 comments
Instructions
Test suite
Solution

Two-fer or 2-fer is short for two for one. One for you and one for me.

Given a name, return a string with the message:

One for X, one for me.

Where X is the given name.

However, if the name is missing, return the string:

One for you, one for me.

Here are some examples:

Name String to return
Alice One for Alice, one for me.
Bob One for Bob, one for me.
One for you, one for me.
Zaphod One for Zaphod, one for me.

Source

https://github.com/exercism/problem-specifications/issues/757

Submitting Incomplete Solutions

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

two-fer.t

#!/usr/bin/env perl
use Test2::V0;
use JSON::PP;

use FindBin qw($Bin);
use lib $Bin, "$Bin/local/lib/perl5";

use TwoFer qw(two_fer);

my $C_DATA = do { local $/; decode_json(<DATA>); };
plan 4;

imported_ok qw(two_fer) or bail_out;

for my $case ( @{ $C_DATA->{cases} } ) {
  is $case->{input}{name}
    ? two_fer( $case->{input}{name} )
    : two_fer(),
    $case->{expected}, $case->{description};
}

__DATA__
{
  "exercise": "two-fer",
  "version": "1.2.0",
  "cases": [
    {
      "description": "no name given",
      "property": "twoFer",
      "input": {
        "name": null
      },
      "expected": "One for you, one for me."
    },
    {
      "description": "a name given",
      "property": "twoFer",
      "input": {
        "name": "Alice"
      },
      "expected": "One for Alice, one for me."
    },
    {
      "description": "another name given",
      "property": "twoFer",
      "input": {
        "name": "Bob"
      },
      "expected": "One for Bob, one for me."
    }
  ]
}
package TwoFer;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw(two_fer);

use experimental qw(signatures);

sub two_fer ($name = 'you') {
    "One for $name, one for me.";
}

1;

__END__

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?