perl version of the same algorithm implemented in ruby