SPUG: Optimizing replace code

Chris Sutton chris at smalldognet.com
Fri Jan 21 01:12:26 CST 2000


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