Inserting into long delimited string using perl.

Hi,

I have a very long pipe delimited string. The length of the string could vary. For example:

 
START|one|two|three|four|five|six|seven
START|one|two|three|four|five|six|seven|eight|nine
START|one|two|three|four

I want to replace in the third occurence of string with another string. For example:

 
START|one|two|here|four|five|six|seven
START|one|two|here|four|five|six|seven|eight|nine
START|one|two|here|four

How do I do this in PERL.

Remember that the occurance to be replaced could be 99th from beginning and the whole string could be delimited with pipe upto say 200 times.
So simple regex with three four entries would not suffice.

why not with sed..?

sed 's/pattern/replace_pattern/3'  file

Like I said I am doing it in perl code. It also has the substitution feature.
Can you write the search pattern. It needs to be generic in nature meaning it should replace the 54th occurance while required and 99th occurance when required. In short it should substitute any nth occurance.

perl -lne 'BEGIN{$occurence = 3 }{ @out=split /\|/ ; $out[$occurence] = "here" ; print join "|" , @out } ' 123.txt
START|one|two|here|four|five|six|seven
START|one|two|here|four|five|six|seven|eight|nine
START|one|two|here|four

---------- Post updated at 04:00 AM ---------- Previous update was at 04:00 AM ----------

Appreciate the response.
Can't it be done via normal regex substitution?

I am saying this because the actual string which I will substitute is not so simple but complex and I cannot simply join it with pipes. I am not looking to split and then join the line but to simple insert at correct position.

what is problem using sed..?

This is not a one liner problem to be solved with sed.
I am coding with perl and want some perl code preferably substitution.

Try:

#!/usr/bin/perl
use strict;
use warnings;
my $n=2;

while(<>) {
 my $count=0;
 my @arr = split /[|]/,$_,-1;
 foreach (@arr) {
  if(/\Apatt\Z/) {
   $count++
  }
  if($count == $n) {
   s/patt/repl/;
   last
  }
 }
 $_ = join '|', @arr;
 print
}

Replace n , patt and repl as per your requirement.

Thanks! I will try them and get back.