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

[CLOSED] Dereference hash into hashes by key

by mlodato (Acolyte)
on May 22, 2018 at 16:04 UTC ( [id://1215047]=perlquestion: print w/replies, xml ) Need Help??

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

O Wise Ones,
Is there a one-line way to do something along the lines of:
my $hash = { key1 => 'value1', key2 => 'value2', }; my ($hash1, $hash2) = _insert_perl_magic_;
Such that then $hash1 becomes {key1 => 'value1'} and $hash2 becomes {key2 => 'value2'}?

The closest I've gotten is:

my @hashes = map { {$_ => $hash->{$_}} } qw(key1 key2); my ($hash1, $hash2) = @hashes;
But it doesn't seem to work in one line (probably because of some lazy generation or something (I confess I don't truly understand how map works)

Replies are listed 'Best First'.
Re: Dereference hash into hashes by key
by soonix (Canon) on May 22, 2018 at 16:28 UTC
    1. What exactly did you try?
      my ($hash1, $hash2) = map { {$_ => $hash->{$_}} } qw(key1 key2);
      works for me.
    2. How did you check the content of $hash1 and $hash1 afterwards? Perhaps you had it right but didn't see it...
      See above response. Thanks for your help!
Re: Dereference hash into hashes by key
by LanX (Saint) on May 22, 2018 at 16:08 UTC
    There is no reason why your own solution shouldn't work in one line, if it works in two.

    Could you please reproduce the problem? What do you get?

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery

      Well this is embarrassing. I scrolled back through my repl history and saw that I had typed ($hash1, $hash1) = ... Thanks!
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-04-25 16:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found