I need to localise some variables in another package, but I won't know what their names are until they are passed in. My attempts to use local
with typeglobs didn't work, so I have fallen back to saving the value of the variable and restoring it manually. Is there a better way? Note, the error checking to see if a variable exists before mucking with it has been elided for clarity.
#!/usr/bin/perl
use strict;
use warnings;
my %orig;
for my $name (qw/foo bar baz/) {
my $var = \${$meta::{$name}};
$orig{$name} = $$var;
$$var = $$var * 2;
}
meta::p();
for my $name (keys %orig) {
my $var = \${$meta::{$name}};
$$var = $orig{$name};
}
meta::p();
package meta;
BEGIN {
our $foo = 1;
our $bar = 2;
our $baz = 3;
}
sub p { print join(" :: ", $meta::foo, $meta::bar, $meta::baz), "\n" }
I am trying to avoid an eval like this:
my $eval = '';
for my $name (qw/foo bar baz/) {
$eval .= "local \$meta::$name = \$meta::$name * 2;\n";
}
eval "$eval meta::p()";
meta::p();
Is trying to avoid the eval a waste of time? Is the new code worse than the eval?
Note, I also don't want to use symbolic references, all code must work under strict
. The current solution works, so I am not looking for hacks to get around what I am doing, I am looking for a better solution (if one exists).