my @items = split /\s+/, $buf; if (scalar(@items) == 13) { # process (ii) } else { # process (i) or (iii) } #### use strict; use warnings; while () { my @items = split /\s+/, $_; if (scalar(@items) == 13) { my (@new) = ($items[4] =~ /(PV)(.*)/); my (@new2) = ($items[8] =~ /(RL)(.*)/); splice @items, 4, 1, @new; splice @items, 9, 1, @new2; } print "@items\n"; # now @items always contains same number of tokens # process items... } __DATA__ SS 21 PL 2#3 PV 51.3 CL #110 +0 RL 126' SA 106 DS 93 SS 21 PL 2#3 PVa51.3 CT^ 110 +0 RL126, SA 106 DS 93 SS 21 PL 2#3 PV 51.3 CL #110 +0 RL 126' SA 106 DS 93 #### SS 21 PL 2#3 PV 51.3 CL #110 +0 RL 126' SA 106 DS 93 SS 21 PL 2#3 PV a51.3 CT^ 110 +0 RL 126, SA 106 DS 93 SS 21 PL 2#3 PV 51.3 CL #110 +0 RL 126' SA 106 DS 93