Dave's Brain

Browse - programming tips - replacing dollar variables

Subject: Replacing dollar variables
Date: 2007nov28
Language: Perl, C

Q.  How would you replace $variables in some text?

A.  I'll give you the answer in 2 languages.

In Perl:

sub main()
{
        my($buf, %val);

        $buf = 'hello $person, how are you?';
        $val{person} = 'Joe';

        $buf =~ s/\$(\w+)/$val{$1}/eg;
	# The e is key here.  It means the replacement value is Executed

        print "Result: $buf\n";
}

In C:

While not totally bulletproof, this function does the trick.

// First, a small helper function
inline char *Shuffle(char *dest, const char *src)
{
	return (char *) memmove(dest, src, strlen(src) + sizeof(char));
}

/*
parameters:
buf:   A NUL-terminated buffer that may or may not contain a dollar variable
       eg "hello $person, how are you"" 
szVar: The name of the variable to replace.  "person" in this example.
szVal: The new value for the variable.  eg "Joe".
       If the size of this new value is larger the size allocated for buf
       we'll have a buffer overflow.  So don't allow szVal from untrusted
       users.
*/
void ReplaceVariable(char *buf, const char *szVar, const char *szVal)
{
	char *	p = buf;
	size_t	lenVar = strlen(szVar);
	size_t	lenThisVar;

	while ((p = strchr(buf, '$')) != NULL)
	{
		lenThisVar = strspn(p+1, "abcdefghijklmonpqrstuvwxyz");
		if (lenThisVar == lenVar && strncmp(szVar, p+1, lenThisVar) == 0)
		{
			Shuffle(p+strlen(szVal), p+1+lenThisVar);
			memcpy(p, szVal, strlen(szVal));
			p += strlen(szVal);
		}
	}
}

// Example use:
void main()
{
	char	buf[1024] = "Hello $person, how are you?";

	ReplaceVariable(buf, "person", "Joe");
	printf("Result: %s\n", buf);
}

If you want a full-fledged templating system, check out:
http://code.google.com/p/google-ctemplate
And there are many others.

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.