$ perl -Mstrict -Mwarnings -le ' my @wtodays= q{cOne cTwo cThree 13 sec cFour cOne cTwo cThree 11 sec cFour cOne cTwo cThree 1 min 2 sec cFour cOne cTwo cThree 13 sec cFour}; my $re = qr{ ^ # anchor: start of line \s* # discard: possible whitespace (\w+) # capture: cOne \s+ # discard: whitespace (\w+) # capture: cTwo \s+ # discard: whitespace \w+ # discard: cThree \s+ # discard: whitespace ((?:\d+ \s+ min \s+)? \d+ \s+ sec) # capture: possible min and sec \s+ # discard: whitespace (\w+) # capture: cFour \s* # discard: possible whitespace $ # anchor: end of line }mx; my @table_data; for (@wtodays) { while (/$re/g) { push @table_data => [$1, $2, $3, $4]; } } { local $" = "|"; for (@table_data) { print "@$_"; } } ' cOne|cTwo|13 sec|cFour cOne|cTwo|11 sec|cFour cOne|cTwo|1 min 2 sec|cFour cOne|cTwo|13 sec|cFour