while () { $_ =~ s/ #substitute (?<=\d) # find position having 1 number preceeding it (?=(\d\d\d)+(?!\d)) # ant the position have 1 or more groups of three numbers following it with a non-number at the end /,/ # put a comma at this position g; # do this substitution golbally print "$_"; } __DATA__ 123 1234 12345 123446 1234567 1234567.1234