Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
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 drinking their drinks and smoking their pipes about the Monastery: (13)
As of 2015-07-01 15:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (8 votes), past polls