use strict; my @names = ( 'Joe John Smith', 'David George', 'Emma Harry Sally Martin', ); foreach (@names) { my @w = split /\s/, (/\s+(\w[\w ]{0,18}\w)\s*$/)[0]; shift @w while @w > 2; print "@w\n"; }