use strict; use warnings; my @strs = ( "j k l foobar", "foobar", "jkl foobar", "1 2 3", "jk l foobar", "foobar j k l", "foobar j kl", " ", " ", "j jk foobar", "j k jk foobar", "j k l" ); my @sanitisedNames = (); for my $str (@strs) { my $oStr = $str; $str =~ s/\G([a-z])\s+(?!\w{2})/$1/gi; $str =~ s/\s+/ /g; push @sanitisedNames, [$oStr, $str]; } printf "%-25s >%s<\n", @$_ for (@sanitisedNames);