http://www.perlmonks.org?node_id=937235

metaperl has asked for the wisdom of the Perl Monks concerning the following question:

I need to set package variables in the package 'main' to the value of a key with the same name. I thought the code below would do it:

sub globalize_weightframe { my ($i)=@_; warn "Globalize was passed $i."; my %w = %{$hangar->{stops}[$i]{weightframe}}; for my $val (keys %w) { eval "$main::$val = $w{$val}"; warn "globalize $val - $w{$val}"; } }
but printing the value of one of the globals after calling this sub does not yield anything, whereas it does in the warn right within this sub.

Any help on setting a set of package variables in this way is appreciated.

Replies are listed 'Best First'.
Re: Setting package variables via eval
by BrowserUk (Patriarch) on Nov 09, 2011 at 22:39 UTC

    The text $main in your eval is being taken as a variable of that name. Escape the $.

    But you shouldn't need to use eval. This works for me:

    my $var = 'fred'; ${"main::$var"} = 12345; ## set main::fred = 12345

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.