Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Looking for equivalent to LHS eval

by elbie (Curate)
on Jul 17, 2003 at 15:37 UTC ( #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?


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,

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://275251]
Approved by grinder
[davido]: Lol, in composing test code for Re: Stupid, yet simple, sort question I managed to fill up /tmp for a moment, causing bash to complain about "pmbash: cannot create temp file for here-document: No space left on device"
[davido]: hm, sorry, wrong link: Re^3: Perl Program to efficiently process 500000 small files in a Directory (AIX) should be it.

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2018-03-18 06:59 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (228 votes). Check out past polls.