jpfarmer has asked for the wisdom of the Perl Monks concerning the following question:
I'm currently working on making some modifications to an internal chat program for my employer. At the moment, I'm making a modification to the way that the author of each post is printed. Currently, it displays "Firstname (Location):" for all users, but I'd like to modify it so that each user can choose their own prompt format.
My end goal is to allow them to create a formatted text string with some kind of markup (like -UN- for username, -LOC- for location, etc) and then have the program stuff that with the appropriate data. My first thought was to use sprintf and simply use a regexp to replace the codes with the appropriate notation. However, this plan was dependant on being able to address the passed parameters out of order, which doesn't seem to be supported until Perl 5.8, and I'm stuck with 5.6 in my production environment.
My next attempt was to create a string with literal variable names in it (for example, $prompt = '$firstname ($location)';, but then I have to come up with a way to fill those literal variables later. Tye suggested something along the lines of s/($\w+)/"$1"/gee (that may not be exactly what he suggested, because I'm writing from memory, but I believe it is close), but that's going to add at least 30 s///'s to my program (one for each line of chat displayed), and I'd like to avoid that many additional operations since this program is run about 150 times/minute. I was warned that evaling the variable wasn't a very good idea either for safety reasons.
I feel kind of stuck at this point, because I don't really know how to fix this. I thought about using an array and, based on which values are substituted, pull out the appropriate array slices. I was thinking something like this (untested) code:
$prompt = "-RN- (-LOC-)"; @user_info = ("juser", "Joe", "3rd floor"); # Here would be some code to do create the sprintf format and # determine the appropriate array slices # $patten is determined to be "%s (%s)" and $slices is determined # to be "1,2"; my $output = sprintf($pattern, @user_info[$slices]);
However, I'm not ever sure something like that can be done, and it seems like a pretty lousy way to do it even if it is possible. I can't help thinking there must be some better way that I just can't come up with.
Any suggestions you may have would be very appreciated.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trying to allow user-customizable prompts in a chat program
by japhy (Canon) on Apr 22, 2004 at 19:59 UTC | |
|
Re: Trying to allow user-customizable prompts in a chat program
by tkil (Monk) on Apr 23, 2004 at 23:28 UTC |