Skip to content

Instantly share code, notes, and snippets.

@MadcapJake
Last active November 1, 2015 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MadcapJake/2c78ea7585143298c66a to your computer and use it in GitHub Desktop.
Save MadcapJake/2c78ea7585143298c66a to your computer and use it in GitHub Desktop.
Translate English to Pig Latin with ease!
given @*ARGS[0] {
when @_ eq '-p' or @_ eq '--phrase' {
say translate(@*ARGS[1]);
}
when @_ eq '-f' or @_ eq '--file' {
say translate(@*ARGS[1].IO.slurp);
}
default {
say 'You must provide either "-p"/"--phrase" and a phrase or "-f"/"--file" and a filepath.';
exit(1);
}
}
sub translate(Str:D $english) { [~] $english.split(/<:!Letter>+/, :all).map: &translate-word }
sub translate-word($word) {
# 'y' is left in the consonants because
# in English it is always a consonant when
# at the beginning of a word.
my $vowels = /<[aeiouAEIOU]>/;
my $consonants = /<:Letter-[aeiouAEIOU]>+/;
given $word {
when $word.match($vowels) and $/.from == 0 {
$word ~ 'yay';
}
when $word.match($consonants) and $/.from == 0 {
samecase(
$word.substr($/.to) ~ $word.substr($/.from, ($/.to - $/.from)) ~ 'ay',
$word
);
}
default { $word }
}
}
@MadcapJake
Copy link
Author

perl6 platin.p6 -p "hello world"
perl6 platin.p6 -f ~/Documents/2005_english_essay14.txt

@b2gills
Copy link

b2gills commented Nov 1, 2015

How about using MAIN multi subs like the following:

#| translate a given phrase into Pig Latin
multi sub MAIN ( Str $phrase, :p(:phrase($))! )
{
    say translate $phrase
}

multi sub MAIN ( *@phrase, :p(:phrase($))! )
is hidden-from-USAGE
{
    say translate ~@phrase
}

#| translate a file into Pig Latin
multi sub MAIN ( Str $file-name, :f(:file($))! )
{
    say translate $file-name.IO.slurp
}

If you called the program with incorrect arguments, or no arguments you would get the following in STDERR
( If you pass in a --help it would get printed to STDOUT )

Usage:
  ./test.p6 -p|--phrase=<Any> <phrase> -- translate a given phrase into Pig Latin
  ./test.p6 -f|--file=<Any> <file-name> -- translate a file into Pig Latin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment