Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Best Practice for replace sub

by tobyink (Abbot)
on Mar 01, 2013 at 12:17 UTC ( #1021235=note: print w/ replies, xml ) Need Help??


in reply to Best Practice for replace sub

Perl 5.10 and above have state variables, but they don't work for hashes and arrays - just scalars. Still, you can use hashrefs/arrayrefs.

sub encode { state $lookup = { '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', map((chr($_), "&#$_;"), (0..31)), }; state $re = do { my $tmp = join('', keys %$lookup); qr/([$tmp])/ } +; my ($text) = @_; return '' unless defined $text; $text =~ s/$re/$lookup->{$1}/g; return $text; }

If you need to support older versions of Perl, then curly braces can be used to limit the scope of lexical variables...

{ my $lookup = { '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', map((chr($_), "&#$_;"), (0..31)), }; my $re = do { my $tmp = join('', keys %$lookup); qr/([$tmp])/ }; sub encode { my ($text) = @_; return '' unless defined $text; $text =~ s/$re/$lookup->{$1}/g; return $text; } }

Or even better (because it delays populating the variables until they're needed):

{ my ($lookup, $re); sub encode { $lookup ||= { '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', map((chr($_), "&#$_;"), (0..31)), }; $re ||= do { my $tmp = join('', keys %$lookup); qr/([$tmp])/ } +; my ($text) = @_; return '' unless defined $text; $text =~ s/$re/$lookup->{$1}/g; return $text; } }
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name


Comment on Re: Best Practice for replace sub
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1021235]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (11)
As of 2014-08-20 16:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (119 votes), past polls