in reply to getting array of values from hash

twinsen,
I hesitated to reply because I knew other monks would come up with a solution faster than I. I only would like to add grep for the possibility that the first array (@a1) contain non-keys as well.

#!/usr/bin/perl -w use strict; my %h1; $h1{'key1'} = 'foo'; $h1{'key2'} = 'bar'; my @a1 = ( 'key1' , 'key2' , 'not_a_key'); my @a2 = grep defined , @h1{@a1}; print "$_\n" foreach(@a2);

Cheers - L~R

Replies are listed 'Best First'.
Re^2: getting array of values from hash
by adrianh (Chancellor) on Mar 25, 2003 at 10:33 UTC
    I hesitated to reply because I knew other monks would come up with a solution faster than I. I only would like to add grep for the possibility that the first array (@a1) contain non-keys as well.

    Niggle :-)

    This doesn't check for non-keys. It checks that each key has a defined value. In the process it auto-vivifies each key in @a1, which is probably not what you want even if you are searching for keys with defined values. For example, after running your example %h1 will be:

    ( 'key2' => 'bar', 'key1' => 'foo', 'not_a_key' => undef, )

    Also, what if you want a key with an undef value?

    If @a1 might contain non-keys they something like this will do the job.

    @a2 = @h1{grep exists $h1{$_}, @a1};
      adrianh,
      I jokingly said in the CB the other day that I wished Perl 6 would have a plug-in (literally), so that I could plug it into my brain and have it directly translate my thoughts to code. I guess I don't need to wait for Perl 6 - just have you around ;-)

      Thanks for writing what I was thinking!

      Cheers - L~R