SPUG: Optimizing replace code

Scott Blachowicz sab at rresearch.com
Fri Jan 21 18:38:38 CST 2000


On Fri, Jan 21, 2000 at 01:32:06PM -0800, El JoPe Magnifico wrote:
> $template =<<END;
> Hello my name is {name} and I am a {function}.
> My hobbies are {hobby1} and {hobby2}, and I have {numpets} pets.
> END
> printinfo( "template", $template );
> 
> ## First run; dumping results into a variable...
> $string1 = replace( $template, {
> 	'name'	=> 'John Doe',
> 	'function'	=> 'perlaholic',
> 	'hobby1'	=> 'hacking',
> 	'hobby2'	=> 'scuba diving',
> 	'numpets'	=> 'zero',
> 	} );
> printinfo ( "string1", $string1 );
> 
> ## Second run; note that the template wasn't munged by previous run's
> ## replace() call, because it worked on a _copy_ of the template...
> printinfo ( "string2", replace( $template, {
> 	'name'	=> 'Eva Gabore',
> 	'function'	=> 'mistress of Green Acres',
> 	'hobby1'	=> 'shopping',
> 	'hobby2'	=> 'getting manicures',
> 	'numpets'	=> 'many, many',
> 	} ) );
> 
> ## Add a title line, follow with a blank line...
> zub printinfo
> {
> 	my ($descrip, $text) = @_;
> 	print "Text of $descrip:\n$text\n";
> }
> 
> ## Here's the magic!
> zub replace
> {
> 	my ($string, $data) = @_;
> 	$string =~ s/{([^}]+)}/$data->{$1}/g;
> 	return $string;
> }

OK...that "([^}]+)" means:

	( - start a tagged section of the input (first open paren gets
	    referred to as $1 in the substitution string).
	[^}] - a negated character class - any non-"}" character matches
	+ - one or more of the previous thing (the char class above)
	) - end a tagged section of the input

As for keeping non-matched text...maybe something in this vein:

zub replace
{
	my ($string, $data) = @_;
	$string =~ s/{([^}]+)}/subst($1,$data)/eg;
	return $string;
}

zub subst
{
	my $substring = shift;
	my $data = shift;
	defined $data->{$substring} ? "$data->{$substring}" : "{$substring}";
}

Don't know about performance issues as I've never really used the 'e'
flag on the s/// command before.

Scott

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    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