Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^2: Hash assignments using map

by njcodewarrior (Pilgrim)
on Feb 24, 2007 at 18:32 UTC ( [id://601903]=note: print w/replies, xml ) Need Help??


in reply to Re: Hash assignments using map
in thread Hash assignments using map

I've got a HoH data structure for which I'm looking to keep only certain entries. The entries I'm looking for are contained in a list and I'd like to eliminate the entries which are not contained in that list ( I've substituted a straight hash in place of my HoH for simplicity's sake):

#! /usr/bin/perl 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 }; my %keepers = map { $_ => 1 } @to_keep; foreach ( keys %h ) { if ( !exists $keepers{$_} ) { delete $h{$_}; } } $Data::Dumper::Varname = 'h'; print Dumper( \%h ); $h1 = { 'c' => 'x', 'a' => 'z' };

I'm creating the %keepers hash out of the items in @to_keep to compare against all of the keys in %h. Since I can create the hash this way:

my @to_keep = qw{ a c }; my %keepers; foreach ( @to_keep ) { $keepers{$_}++; } $Data::Dumper::Varname = 'keepers'; print Dumper( \%keepers ); keepers1 = { 'c' => 1, 'a' => 1 };

I thought I could do the same thing using map:

my @to_keep = qw{ a c }; my %keepers; %keepers = map { $_++ } @to_keep; $Data::Dumper::Varname = 'keepers'; print Dumper( \%keepers ); $keepers1 = { 'a' => 'c' };

But it doesn't seem to work.

njcodewarrior

Replies are listed 'Best First'.
Re^3: Hash assignments using map
by graff (Chancellor) on Feb 24, 2007 at 22:45 UTC
    my @to_keep = qw{ a c }; my %keepers; foreach ( @to_keep ) { $keepers{$_}++; }
    ... I thought I could do the same thing using map ...

    The way to do that with map would be like this:

    my %keepers = map { $_ => 1 } @to_keep;

    The point is that, in this case, you want each iteration in map to return a key/value pair, not just a single value, and the "fat comma" (=>) does that for you.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-16 13:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found