Hole type: subroutine
Write a subroutine that accepts a list of words, and returns the list
sorted by the first vowel that appears in each word. If two words
have the same first vowel, it does not matter which is sorted first.
Words will be in lowercase and will always contain at least one vowel.
(Vowels are a, e, i, o, and u.)
e.g.: hole('dog', 'cat', 'fish', 'duck', 'lemur')
returns: ('cat', 'lemur', 'fish', 'dog', 'duck')
Code | Length |
---|---|
sub hole {map{$_->[0]}sort{$a->[1]cmp$b->[1]}map{[$_,m/[aeiou]/g]}@_} | 58 |
sub hole {sort{($a=~/([aeiuo])/)[0]cmp($b=~/([aeiou])/)[0]}@_} | 51 |
sub hole {sort{($a=~($v='([aeiou])'))[0]cmp($b=~$v)[0]}@_} | 47 |
sub hole {map{substr$_,1}sort map{/[aeiou]/;$&.$_}@_} | 42 |
sub hole {map/.(.+)/,sort map/[aeiou]/&&$&.$_,@_} | 38 |
There are several possible approaches to this problem. The first solution above uses a classic Schwartzian Transform, a map sort map with array references. The second and third pull out the vowels every time the comparison sub is called; the third saves keystrokes by assigning the regex to a variable. The fourth and fifth use the method written about by Uri Guttman and Larry Rosler in their Sort::Fields paper; a map sort map using the default comparison function.