SPUG: Optimizing replace code
El JoPe Magnifico
jope-spug at n2h2.com
Fri Jan 21 18:44:05 CST 2000
On Fri, 21 Jan 2000, Chris Sutton wrote:
> JoPe wins.
And the crowd goes wild! No wait...
those are just the voices in my head. =)
> Just so I (and probably others) can fully understand what is going on
> here can someone explain: ([^}]+)
Character range ([]) consisting of everything except (^)
closing curly bracket (}), with the one-or-more (+) modifier.
The parentheses are so we hold onto it for use later as $1,
in this case in our replacement string. Fairly run-of-the-mill.
> Also, one thing that might make this a little more complicated is that
> if there is not a hash value for a specific {text} string, leave the
> {text} string alone. Right now, it whipes it out.
Rather than.... s/{([^}]+)}/$data->{$1}/g;
this instead... s/{([^}]+)}/$data->{$1} || "{$1}"/eg;
The /e modifier makes the replacement string be interpreted as an
eval expression, rather than a double-quoted (interpolated) string.
Using || to failover to the original string if $data->{$1} is false.
Which means this wouldn't work as expected, if $data->{$1} is 0 (zero).
D'oh! To only have it failover on empty string or undef (the other
two values interpreted as false) use this...
s/{([^}]+)}/$data->{$1} ne '' ? $data->{$1} : "{$1}"/eg;
In this fashion, you can get wicked fancy with your defaulting.
Not sure how adversely the eval from the /e will affect performance.
(if you run benchmarking again, make sure to add the failover behavior
to all applicable sets of code)
-jp
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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