use strict; use warnings; my $max = 5; my $str = '123456789012'; $str =~ s/(\S{$max})(?=\S)/$1 /g; print $str;