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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.