Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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.

Comment on Setting package variables via eval
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2014-12-21 17:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (106 votes), past polls