Hole type: subroutine
Write a subroutine that accepts a string which may consist of a
repeating pattern, and returns the smallest repeating substring. If
the string does not consist of a repeating pattern, the subroutine
should return undef or the empty string.
e.g.:
input output 'aaaaaa' 'a' 'ababab' 'ab' 'aabaab' 'aab' 'ababaa' ''
Code | Length |
---|---|
sub hole {pop=~/^(.+?)\1+$/&&$1} | 21 |
This hole is tricky, because the subroutine is being called in scalar context. Otherwise the result of the pattern match could be returned directly. The obvious way to work around that is with (pop=~/^(.+?)\1+$/)[0]; but changing to the solution shown above saves... one whole character! :)
A shorter solution is pop=~/^(.+?)\1+$/;$1, but that depends on $1 already being empty when the subroutine is called, which may not be the case. This possibility was accounted for in the test data at the conference.