use encoding 'UTF-8'; $string = "this\tis a\ncool\ftest\r"; $string =~ s/(\s)/$spaces{$1}/g; print $string;