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

Setting package variables via eval

by metaperl (Curate)
on Nov 09, 2011 at 22:23 UTC ( [id://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 (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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-19 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found