Skeeve has asked for the wisdom of the Perl Monks concerning the following question:
Hi
I often find myself writing code like this:
# Encoding stuff#################################### my %ENCODE=( '"' => '"', '&' => '&', '<' => '<', '>' => '>', map((chr($_), "&#$_;"), (0..31)), ); my $ENCODE= join('', keys %ENCODE); $ENCODE= qr/([${ENCODE}])/; sub encode { my($text)= @_; return '' unless defined $text; $text=~ s/$ENCODE/$ENCODE{$1}/g; return $text; } ####################################################
Note: Please don't tell me about moduls being able to do exactly this encoding/replacements as this is just an example for several tasks where I need to replace substrings with other strings.
My bad feeling about this is: I'm using kind of global variables which I initialize once because I simply don't want to assign the hash (%ENCODE) and the accompanying scalar ($ENCODE) each time the encode($string) is invoked. So they need to be on global level. But it does not "feel right".
What's your proposal against this? Or what's your view on this?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Best Practice for replace sub
by tobyink (Canon) on Mar 01, 2013 at 12:17 UTC | |
|
Re: Best Practice for replace sub
by tmharish (Friar) on Mar 01, 2013 at 10:11 UTC | |
|
Re: Best Practice for replace sub
by Anonymous Monk on Mar 01, 2013 at 16:05 UTC | |
by tobyink (Canon) on Mar 01, 2013 at 16:56 UTC |