I'd read it into a (tied) 2 dimensional array: a b c d And write it out exchanging inner and outer loop: a c b d