in reply to [Answered!] Taking a subset of a hash

Does anyone know an elegant way to write this?

Perhaps?

my %small_hash; my @retain = grep{ defined $config{ $_ } && $config{ $_ } ## not false } @interesting_keys; @small_hash{ @retain } = @config{ @retain }; return \%small_hash;

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re^2: Taking a subset of a hash
by Narveson (Chaplain) on Oct 30, 2010 at 13:28 UTC

    Sorry if I forgot to mention that $config was a reference.

    Doesn't defined $config{ $_ } && $config{ $_ } have the same truth value as $config{ $_ }?

      Doesn't defined $config{ $_ } && $config{ $_ } have the same truth value as $config{ $_ }?

      Yes. I was attempting to capture your stated requirements:

      but omits them if their configured value is false, undefined, or nonexistent.

      and got it wrong. It should be:

      exists $config{ $_ } && $config{ $_ }

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.