pinpe has asked for the wisdom of the Perl Monks concerning the following question:

Hi, How do I insert character (e.g. , or .) at certain positions in a line? For example I want to insert a period ( . ) after the first 4 characters of every each line in the file. I cannot do it in sed command. I'm playing with my script using perl command but to no avail. Please advice. Thanks in advance. See below: Input:
12345 67890 23456 78901 34567
Desired Output:
1234.5 6789.0 2345.6 7890.1 3456.7
Br, Pete

Replies are listed 'Best First'.
Re: Inserting a character to a line
by pc88mxer (Vicar) on Mar 22, 2008 at 01:08 UTC
    Two approaches come to mind:
    substr($x, 4, 0, "."); # method 1 $x =~ s/\A(....)/$1./; # method 2
    The second approach can also be implemented with sed:
    sed -e 's/^(....)/\1./'
    Anchoring the regular expression using ^ may not be necessary depending on your situation.
      Hi pc88mxer, Cool!! method 2 works on me! Tnx bro! Br, Pete
Re: Inserting a character to a line
by ikegami (Patriarch) on Mar 22, 2008 at 01:27 UTC
    A few ways:
    substr($_, 4, 0, '.'); # at least 4 characters long substr($_, 4, 0) = '.'; # at least 4 characters long $_ =~ s/^(.{4})/$1./; $_ =~ s/(?<=^.{4})/./; pos($_)=4; $_ =~ s/\G/./; # at least 4 characters long $_ .= '.' . chop($_); # exactly 5 chars long $_ /= 10; # a 5 digit number without leading 0s $_ = sprintf('%06.1f', $_/10); # a 5 digit number

    The first one is probably fastest and the clearest.