DEV Community

Discussion on: Daily Challenge #48 - Facebook Likes

Collapse
 
choroba profile image
E. Choroba • Edited

Perl solution. The special array @_ contains the arguments of a subroutine, but in scalar context it returns the number of them.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub likes {
    my $count = @_ - 2;
    sprintf((('no one',
              '%s',
              '%s and %s',
              '%s, %s, and %s',
    )[scalar @_] || "%s, %s, and $count others")
    . ' like%s this', @_[0 .. (@_ > 3 ? 1 : $#_)], 's' x (@_ < 2))
}

use Test::More tests => 5;

is likes(), 'no one likes this';
is likes('Peter'), 'Peter likes this';
is likes('Jacob', 'Alex'), 'Jacob and Alex like this';
is likes('Max', 'John', 'Mark'), 'Max, John, and Mark like this';
is likes('Alex', 'Jacob', 'Mark', 'Max'), 'Alex, Jacob, and 2 others like this';

0xford comma included.