Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Hash assignments using map

by Not_a_Number (Prior)
on Feb 25, 2007 at 10:32 UTC ( [id://601973]=note: print w/replies, xml ) Need Help??


in reply to Hash assignments using map

Here's another way to do what you want, without creating an intermediate %keepers hash:

use strict; use warnings; use Data::Dumper; # Data Structure my %h = ( 'a' => 'z', 'b' => 'y', 'c' => 'x', 'd' => 'w', ); my @to_keep = qw{ a c }; %h = map { $_ => $h{$_} } @to_keep; print Dumper \%h;

Update: If by chance your @to_keep array might contain elements that do not necessarily occur as keys in your input hash, it would probably be better to change the penultimate line to:

%h = map { $_ => $h{$_} } grep { defined $h{$_} } @to_keep;

Replies are listed 'Best First'.
Re^2: Hash assignments using map
by njcodewarrior (Pilgrim) on Feb 25, 2007 at 13:41 UTC

    Hello there Not a Number

    That's very nice and simple!

    Thanks very much for your help! - njcodewarrior

Re^2: Hash assignments using map
by ikegami (Patriarch) on Feb 25, 2007 at 18:58 UTC

    %h = map { $_ => $h{$_} } @to_keep;
    is the same as
    %h = @h{@to_keep};

    Update: Oops, no! It would actually be equivalent to the more complicated:

    my %temp; @temp{@to_keep} = @h{@to_keep}; %h = %temp;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-24 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found