Christopher J. Bottaro wrote:
say i have two strings "xxxxyyyyxxxx" and "zzzz".  i want to
replace characters 4-7 in the first string with the second string
with an emphasis on speed.

basically i want to do what can be done in c with the following:

char str1[13] = "xxxxyyyyxxxx";
char *str2 = "zzzz";
strncpy(str1+4, str2, 4);

so far all i can come up with in perl is:

my $str1 = 'xxxxyyyyxxxx';
my $str2 = 'zzzz';
$str1 = substr($str1, 0, 4) . $str2 . substr($str1, 8, 4);

now obviously the c code is always going to be faster, but is there
any way i can optimize the perl code?  in answering the question,
please note that i only have offsets into the string to work with,
i.e. i can't say $str1 =~ s/yyyy/$str2/;  to be more clear:  "i
want to replace characters n thru m with a new string of length
m-n, but i don't know what characters n thru m are."

You can use substr() as an rvalue:

    substr($str1, 4, 8 - length $str1, $str2);

or if the length of $str1 is given:

    substr($str1, 4, -4, $str2);            # probably fastest

The s/// operator can be used like this:

    $str1 =~ s/^(.{4}).{4}/$1$str2/;

To find out which is actually fastest, you may want to do a benchmark
using the Benchmark module.

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to