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 |