Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1021235]
help
Chatterbox?
[james28909]: Good morning!
[james28909]: I have a problem I am trying to solve. I am packaging scripts using pdk and would like the verify the executable name each time it is executed
[Corion]: Hi James!
[james28909]: I looked through the docs, and see that PerlApp::exe() is suppose to return this information but whenever i try to use this, i get the error "Undefined subroutine &PerlApp::exe called"
[james28909]: i just want to verify the integrity of the executables name each time it is run.
[Corion]: Weird. this documentation says what you say.
[Corion]: I assume you are experiencing this with your packaged program. Maybe also include PerlApp.pm in the packaging list?
[james28909]: has anyone else run into this problem? i have tried searching but have not returned many results
[james28909]: ah, good idea.
[Corion]: What does print $PerlApp::VERSION output?

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2017-07-28 13:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I came, I saw, I ...
























    Results (429 votes). Check out past polls.