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% --
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|