algorithm stuff in perl