Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Setting package variables via eval

by metaperl (Curate)
on Nov 09, 2011 at 22:23 UTC ( #937235=perlquestion: print w/replies, xml ) Need Help??

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 (Pope) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://937235]
Approved by BrowserUk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2020-09-18 14:27 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (112 votes). Check out past polls.