Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Looking for equivalent to LHS eval

by elbie (Curate)
on Jul 17, 2003 at 15:37 UTC ( [id://275251]=perlquestion: print w/replies, xml ) Need Help??

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

I'm parsing a hash, and while I should be keeping them in the hash, there are reasons not to. I dunno. Maybe I should rewrite the program, but in the meantime, I actually want to assign a few of those pairs to variables named after the keys of the hash.

I was hoping I could do something like the following:

for my $key ( qw/key1 key2 key3/ ) { eval( "${$key}" ) = $hash{$key}; }
or something similar. Is there a way to do this?

elbieelbieelbie

Replies are listed 'Best First'.
•Re: Looking for equivalent to LHS eval
by merlyn (Sage) on Jul 17, 2003 at 15:47 UTC
Re: Looking for equivalent to LHS eval
by Zaxo (Archbishop) on Jul 17, 2003 at 15:49 UTC

    If you really want symbolic references,

    { no strict qw/refs vars/; for my $key ( qw/list of keys/ ) { next if $key =~ /\W/ or $key =~ /^\d/; ${$key} = $hash{$key}; } }
    I'm curious to know why you want this.

    After Compline,
    Zaxo

Re: Looking for equivalent to LHS eval
by simonm (Vicar) on Jul 17, 2003 at 15:45 UTC
    Yup, it's just a matter of figuring out what gets quoted; this should do it:
    %hash = ( key1 => 'A', key2 => 'B', key3 => 'C' ); for my $key ( qw/key1 key2 key3/ ) { eval( '$' . "$key = \$hash{\$key}"; } print $key1 . $key2 . $key3;
      Uh, no. You really really don't want to do this. This would be the greater of two evils, the lesser of which would be using symbolic references. And if that's discouraged, using eval to do the same thing is discouraged-squared. {grin}

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

Re: Looking for equivalent to LHS eval
by Aristotle (Chancellor) on Jul 17, 2003 at 16:28 UTC
    The only sane method is using a second hash.
    my %copy_to = ( key1 => \$key1, key2 => \$key2, key3 => \$key3, ); while(my ($key, $var) = each %copy_to) { $$var = $hash{$key}; }

    Makeshifts last the longest.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-25 19:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found