There are a few more solutions that you could have used.

First and foremost, use a Safe. For example:

use Safe; my $config = Safe->new; *{ $config->varglob($_) } = $handler{$_} for keys %handler; $ok = $config->reval( $cfg_str ); # Or: $ok = $config->rdo( $config_source ); $err = $@;
When you are done, you can simply throw away the Safe object, and everything is totally cleaned up.

Secondly, (if using regular string eval, and not a Safe) you could have added the following to your $cfg_str:

join ";\n", map "local *$_ = \$handler{$_}", keys %handler;
That would have cause the local to be undone the moment the string eval finished running.

Thirdly, you could have used recursion:

local *handler_localizer = sub { if( my $name = each %handler ) { no strict 'refs'; local *{$name} = $handler{$name}; handler_localizer(); } else { $ok = eval $cfg_str; $err = $@; } };
But this is silly, when a Safe is so much simpler.

In reply to Re: A useful use of goto by BenGoldberg
in thread A useful use of goto by Corion

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.