The most flexible solution, and the one least likely to confuse coworkers, would be to split the string, test column 16, replace column 16, create a new string w/ join. e.g.:
sub split_join { my $line = shift; my @tokens = split /[|]/, $line; if ($tokens[15] eq 'STOCK') { $tokens[15] = 'BOXXE'; return join('|',@tokens); } else { return $line; } }
But the regex approach will run faster (by 77% according to my tests).
use strict; use warnings; use Benchmark qw(cmpthese); my $line = <DATA>; printf "Original: $line"; printf " split: %s",split_join($line);; printf " simple: %s",simple_regex($line);; cmpthese(5000, { splitjoin => sub {split_join($line)}, simple_regex => sub {simple_regex($line)}, }); sub split_join { my $line = shift; my @tokens = split /[|]/, $line; if ($tokens[15] eq 'STOCK') { $tokens[15] = 'BOXXE'; return join('|',@tokens); } else { return $line; } } sub simple_regex { my $line = shift; #$line =~ s/^((?:[^|]*\|){15})STOCK/${1}BOXXE/; $line =~ s{^ ( (?: [^|]* \| ) {15} ) STOCK } {${1}BOXXE}x; return $line; } __DATA__ AT0000937503|20060530|||142.708534||GROUP AG|30618720||||OPEN|ISIN|494 +3402|VSE|STOCK|39600000|0.77320|STOCK|test
Results:
Original: AT0000937503|20060530|||142.708534||GROUP AG|30618720||||OPE +N|ISIN|4943402|VSE|STOCK|39600000|0.77320|STOCK|test split: AT0000937503|20060530|||142.708534||GROUP AG|30618720||||OPE +N|ISIN|4943402|VSE|BOXXE|39600000|0.77320|STOCK|test simple: AT0000937503|20060530|||142.708534||GROUP AG|30618720||||OPE +N|ISIN|4943402|VSE|BOXXE|39600000|0.77320|STOCK|test Rate splitjoin simple_regex splitjoin 4274/s -- -44% simple_regex 7576/s 77% --

In reply to Re: Search and replace the word in Column 16 by imp
in thread Search and replace the word in Column 16 by chanakya

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.