my @parts = split /(\s+)/, $message; # parents preserve spaces # operate on @parts as in the OP my $filtered = join '', @parts;