#!/usr/bin/perl -w
#######################
# jims_piglatin.pl
#
# demo of perl regular expressions that
# translates english standard input to piglatin standard output.
#
# For this exercise, piglatin is 
# (from http://www.math.luc.edu/~glance/Spr02/225on/Projects/lab3/225Lab3.htm)
#
# -------------------------------------------------
#  If the first letter of the word is a vowel 
#     ("a", "e", "u", "i", or "o"), then append "way" to the end of the word.
#  
#  Otherwise:
#         1. Move all letters before first useable vowel to end of word. 
#            A usable vowel is ...
#              a) any "a", "e", "u", "i", or "o"
#              b) any "y" that is not the first character of the word
#         2. Add "ay" to the end of the word
# (These rules are simple, not perfect.)
# --------------------------------------------------
#
# Usage: ./jims_piglatin <input.txt > output.txt
#
# I'm sure there are *much* shorter ways, but here's the first one I came up with.
#
# Jim Mahoney, Oct 29 2003
#######################
use strict;

my $input = join('',<STDIN>);
my @words = split(/\b/,$input);

foreach my $word (@words){
  # Here a "word" is anything between word boundries, which
  # also includes non-word things like spaces, newlines, and punctuation,
  # all of which should be passed through unchanged.
  
  if    ($word =~ /^[aeiou]/i){    # If it starts with vowel,
    # print "vowel start : '$word', appending 'way' to get ";
    $word .= 'way';                         #   then append 'way'.
    # print "'$word'\n";
  }
  elsif ($word =~ /^qu(.+)$/){     # If it starts with qu, move those to the end
    $word = "$1quay";
  }
  elsif ($word =~ /^[a-z]/i){               # If it starts with another letter,
    # print "consanant start : '$word' ";
    $word =~ m{(
                 (([^aeiouy]+)(y))          #   at least one non-vowel then y
                 |                          #   or
                 (([^aeiou]*)([aeiou]))    #    0-any non-vowels then aeiou
               )
               (.*)                         #   rest of word
              }ix;
    # either 3,4,8  or 6,7,8
    my $one   = ($3 or $6 or '');           #   leading non-vowels
    my $two   = ($4 or $7 or '');           #   usable vowel
    my $three = ($8 or '');                 #   anything after the usable vowel
 
    # print " after match: '$one', '$two', '$three'";
    # print " => $two$three$one"."ay\n";
    $word = "$two$three$one".'ay';          #   move front to back; add 'ay'
  }

  # If there's a capital letter in the word, 
  # make lowercase and then capitalize the first character.
  if ($word =~ /[A-Z]/){
    $word = lc($word);       # make the whole thing lowercase
    $word = ucfirst($word);  # and capitalize the first letter.
    # Note that $word="\u\L$word" also workss.
  }

  # And send it on to the output.
  print $word;
}

