Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks! ok - i'm experimenting with hashes and want to be able to look for the presence of certain keys in a hash and then simply print the corresponding values to those keys. Hope someone can help!
my @array = ('sarah', 'john'); # stores the keys i'm interested in my %hash = ( 'sarah' => '19', 'john' => '25', 'emma' => '22', ); if (exists ($hash{$array[0]})) { print value; }

Replies are listed 'Best First'.
•Re: extracting values from hashes
by merlyn (Sage) on Mar 18, 2003 at 13:49 UTC
    Given that you spoke only abstractions, like "array" and "hash", I would suspect this is homework.

    However, you access the value of a hash in the same way you used exists. So you were mostly there.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: extracting values from hashes
by broquaint (Abbot) on Mar 18, 2003 at 13:55 UTC
    my @array = qw/sarah john/; my %hash = ( sarah => 19, john => 25, emma => 22, ); print "$_: $hash{$_}\n" for grep exists $hash{$_}, @array; __output__ sarah: 19 john: 25
    See. exists and grep for more info.
    HTH

    _________
    broquaint

      thanks for your help broquaint, this makes sense, but how would it be possible to push the information on the print line into an array as the following doesn't work;
      push @data, "$_: $hash{$_}\n" for grep exists $hash{$_}, @array;
        If you just want the array elements that exists as keys in the hash, a simple grep() should do the job.
        my @array = qw/sarah john/; my %hash = ( sarah => 19, john => 25, emma => 22, ); ## push() would be superfluous my @data = grep exists $hash{$_}, @array; print "data: @data\n"; __output__ data: sarah john

        HTH

        _________
        broquaint