Chapter 8
sv_insert(sv, offset, length, "string to insert", strlen("string to insert"));
The next example shows how to remove characters from the start of a string:
SV *sv = newSVpv("Just another Perl hacker.", 0);
sv_chop(sv, SvPVX(sv) + 13); // sv contains "Perl hacker" after this
The second parameter to sv_chop is a pointer into the string to the new first
character.
If you need to do substring searches over a large string, you can speed up the
process using the Boyer Moore search algorithm.
3
This is done by first compiling
the SV to be searched for with fbm_compile()
4
and then searching with fbm_instr().
For example, here's a function that takes two SVs and returns the offset o f the
second inside the first or 1 on failure. This function uses SvPVX and SvEND
5
so it's
only safe to call if both SVs are SvPOK() real code would include the necessary
checks and conversions of course!
int fast_search (SV *source, SV *search) {
char *found; // pointer to hold result of search
// compile search string using Boyer Moore algorithm
fbm_compile(search, 0);
// conduct the search for the search string inside source
found = fbm_instr(SvPVX(source), SvEND(source), search, 0);
// if the search failed, return 1
if (found == Nullch) return 1;
// return the offset of search within source
return found SvPVX(source);
}
In my tests (looking for a single word in a string containing all of /usr/dict/words),
this version was between two and three times faster than a version that used Perl's
index() function.
3. Boyer Moore is a search algorithm that matches without examining every character. It has
the unusual feature of actually going faster the longer the match string is.
4. Note that fbm_compile() modifies the SV passed to it. As a result, it can't be used on constant
SVs like those produced from string constants.
5. A macro that returns a pointer to the end of the string inside an SV
182
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved