in reply to hashes - finding values

Because exists checks for the existence of keys and not values. Instead a grep might be better suited e.g
my @array = qw/ foo bar baz quux /; my %hash = qw/ f1 baz f2 foo /; my @newarray; foreach my $thing (@array) { push @newarray, $thing if grep { $_ eq $thing } values %hash; } print "newarray - @newarray\n"; __output__ newarray - foo baz
This isn't terrifically optimal so you may want to create another hash where the values are the keys (although the solution starts to look like finding an array intersection which is another option).
HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: hashes - finding values
by Anonymous Monk on Jul 03, 2003 at 13:45 UTC
    Thanks broquaint but I want to push the corresponding keys to the matching values into the new array. I think your code keeps values in the array that are present in the hash.
    my @array = qw/ f1 f2 f3 f4/; my %hash = qw/ f1 foo f2 bar/; #OUTPUT # newarray - foo bar.
    I'm not too sure how to adapt your code to do this!
      Ok, then you'll want something like ...
      my @array = qw/ foo bar baz quux /; my %hash = qw/ f1 baz f2 foo /; my @newarray; for my $k (keys %hash) { push @newarray, $k if grep { $hash{$k} eq $_ } @array; } print "newarray - @newarray\n"; __output__ newarray - f1 f2

      HTH

      _________
      broquaint