perl loop refactor