SPUG: Optimizing replace code
Riley
wormwood at speakeasy.org
Fri Jan 21 11:44:25 CST 2000
On second thought, if you really want to light a fire under your script,
skip out on the regexes altogether and try something like this:
sub hash_interpol { # hide yer stash!
my $hash = shift;
my $string = shift;
my ($endpos, $index);
while (($index = index($$string,'{',$index)) > 0) {
$endpos = index($$string,'}',$index);
substr($$string,$index,($endpos-$index)+1) =
$hash->{substr($$string,$index+1,($endpos-$index)-1)};
}
}
This runs about twice as fast as the original code, and 4-5 times as
fast as the eval'd version on my machine.
--Riley
----------------------
CARTHAGO DELENDA EST.
On Fri, 21 Jan 2000, Riley wrote:
>
> I think the problem may be that you're using the eval {} form rather than
> eval "" so that $evalcode is not run-time interpolated before evaluation
> -- it's just returned as a scalar value.
>
> You're getting great efficiency but not compiling any regexes at all!
>
>
> --Riley
> ----------------------
> CARTHAGO DELENDA EST.
>
> On Thu, 20 Jan 2000, Chris Sutton wrote:
>
> > Hello,
> >
> > I have a general purpose function that takes a string like this
> >
> > This {is} a {test}
> >
> > and a hash like this
> >
> > is => "IS",
> > test => "TEST"
> >
> > and spits out
> >
> > This IS a TEST
> >
> > Here is my original code
> >
> > my $hash = shift; #pointer to hash
> > my $string = shift; #pointer to string
> > my $key;
> >
> > foreach $key (keys %$hash) {
> > $$string =~ s/\{$key\}/$$hash{$key}/g;
> > }
> >
> > After going to the December SPUG meeting and learning a bit more about
> > the different efficiencies of regular expressions, it dawned on me that
> > this is pretty slow and doing it the eval way would be much better.
> > (Some testing and benchmarking proved eval to be about 4 times faster).
> >
> > So, here is my new code
> >
> > my $hash = shift; #pointer to hash
> > my $string = shift; #pointer to string
> > my $key;
> >
> > my $evalcode;
> >
> > foreach $key (keys %$hash) {
> > $evalcode .= "\$\$string =~ s/\\{$key\\}/$$hash{$key}/g;";
> > }
> >
> > eval { $evalcode };
> >
> > But for some reason it's not working the way it should and I think it
> > has something to do with the $string pointer but I don't know how it's
> > acting inside the eval.
> >
> > Any pointers? I'm off by a backslash somewhere right?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
POST TO: spug-list at pm.org PROBLEMS: owner-spug-list at pm.org
Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
Email to majordomo at pm.org: ACTION spug-list your_address
More information about the spug-list
mailing list