We have: a hash, i.e. mapping from one set to another; a set.
We need to restrict the domain of this mapping to the set and by the set.
Note: the set may not be a subset of the domain of our mapping.

Restriction to the set:

%h1=( 1=>"one", 2 => "two", 3 => "three", 4 => "four"); @set=(1, 3, 5, 7); my %h2; $h2{$_} = $h1{$_} for grep exists $h1{$_}, @set;

Restriction by the set:

%h1=( 1=>"one", 2 => "two", 3 => "three", 4 => "four"); @set=(1, 3, 5, 7); my %h2 = %h1; delete $h2{$_} for grep exists $h1{$_}, @set;

What about the same for values? (restrict the range to the set and by the set)?

Replies are listed 'Best First'.
RE: Mapping restrictions
by merlyn (Sage) on Sep 14, 2000 at 18:34 UTC

      You are right, absolutely. I have found this solution hour after sending. Really, we sould not include extra pairs, but we can delete anything irrelevant.
      I like solution with map/grep for the first case suggested by runrig.

      But - what about range restrictions? Could somebody suggest nice-looking snippet? I could not yet :(

      -- brother ab
RE: Mapping restrictions
by runrig (Abbot) on Sep 14, 2000 at 20:44 UTC
    Just for variety, another way to do the first one:

    my %h2 = map { $_ => $h1{$_} } grep { exists $h1{$_} } @set;
      And yet another:

      my %h2 = map { exists $h1{$_} ? ($_ => $h1{$_}) : () } @set;