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

Hi dear all
Assuming I have this array and hash.

My @array = qw(world today is nice); my %hash = (0 => "Hello", 1=> "world" , 2=> "today" , 3=> "is" , 4=> " +nice" );
I want to search thought the hash values using the array elements as values and then print the hash keys for each searched value from the array in a new array.
It should print 1 for world, 2 for today, so on which will be saved in the new array
I tried to use lookup with loop thought the array but it did not work.
I used grep also, but did not hot what I want
Any idea about how I can do it???
Thanks in advance

Replies are listed 'Best First'.
Re: Search hash keys using values from array
by thanos1983 (Parson) on Mar 23, 2017 at 12:41 UTC

    Hello AhmedABdo,

    There are many many ways on solving your problem, one way could be:

    I would recommend to read the List::Compare module.

    Be aware in your example that you provided us, the values of the hash is and nice are not one string as in the array so as expected they will not match.

    Update: please every time you update your question / reply provide and update so can follow. You have altered your question and my reply is not suitable to you any more. I will post another reply in a few hours when I will get back to my pc.

    Update2: An alternative solution to your problem:

    Update3: In case you want your keys sorted:

    Update4: Maybe this solution is faster using grep:

    Update5: Maybe map is fast I am not sure though:

    Update6: Maybe smartmatch is fast I am not sure though, but it has been placed as experimental see (The smartmatch family of features are now experimental):

    Update7: I could not resist I benchmark them and here is what I found:

    Please on your next question that you will post on the forum follow the guided lines (How do I post a question effectively?).

    Hope this helps.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: Search hash keys using values from array
by duyet (Friar) on Mar 23, 2017 at 13:29 UTC

    I would use reverse for this:

    my @array = qw(world today is very nice); my %hash = (0 => "Hello", 1=> "world" , 2=> "today" , 3=> "is" , 4=> " +nice" ); my %reversed_hash = reverse %hash; foreach my $word ( @array ) { if ( exists $reversed_hash{ $word } ) { print $reversed_hash{ $word } . "\n"; } else { print "unknown '$word'\n"; } }

    Output:

    1 2 3 unknown 'very' 4
Re: Search hash keys using values from array
by haukex (Archbishop) on Mar 23, 2017 at 10:44 UTC
    I tried to use lookup with loop thought the array but it did not work.

    Could you show us the code you tried? The approaches you describe should work, so perhaps we can help you fix the issues with your code. See How do I post a question effectively?

    Also, are all the values in the hash unique? If so, you could simply build an inverse hash using reverse and use that for lookups.

Re: Search hash keys using values from array
by kcott (Archbishop) on Mar 24, 2017 at 06:27 UTC

    G'day AhmedABdo,

    This looks like an "XY Problem" to me. In addition, it looks like you've typed, rather than pasted, your code, which has resulted in typos: My should be my; "Hello" is either missing from @array, extraneous to %hash, or an explanation of how it relates to the rest of your post has been omitted. I see others have already pointed out further issues: I won't repeat those comments here but I do agree with them.

    Perhaps what you're looking for can be achieved with the enum module. Here's a script with a couple of examples of usage:

    #!/usr/bin/env perl -l use strict; use warnings; use enum qw{world=1 today is nice}; print '"world today" from enum'; print for world, today; print '"today is nice" from array'; my @indices = (today, is, nice); print for @indices;

    Output:

    "world today" from enum 1 2 "today is nice" from array 2 3 4

    — Ken

      Hello kcott,

      In this case enum fits perfect. Thanks for pointing out, I had no idea about it.

      Seeking for Perl wisdom...on the process of learning...not there...yet!

        Glad you liked it.

        Here's another, more complex example of usage, that I posted last month. This shows a method of determining the original token name from the index.

        — Ken

Re: Search hash keys using values from array
by hippo (Archbishop) on Mar 23, 2017 at 10:43 UTC

    See the FAQ.

    I tried to use lookup with loop thought the array but it did not work.

    "It did not work" is as useful to a developer as "I'm ill" is to a medic. Try to be specific.

      AhmedABdo: The specific entry in the FAQ is "How do I look up a hash element by value?" in the "Data: Hashes (Associative Arrays)" section (it cannot be linked to directly for some reason). (Update: Per hippo, failure to link seems to be a "feature" of my browser, IE. Oh, well...)


      Give a man a fish:  <%-{-{-{-<

Re: Search hash keys using values from array
by Eily (Monsignor) on Mar 23, 2017 at 15:04 UTC

    While the proposed solution of reversing the hash is technically correct, I can't help but think that the real solution probably is to construct the hash correctly in the first place.

    Going even further, your question looks like a XY Problem: you are asking about the way to correct an issue that you encountered while trying to solve a bigger problem.

    So I strongly advise you to read How do I post a question effectively? And then post a description of your global problem, and how your array and hash are elements of your attempted solution.

    Edit: Not_a_Number told me my second paragraph was confusing, so I rephrased and went straight to the point.

Re: Search hash keys using values from array
by 1nickt (Canon) on Mar 23, 2017 at 10:43 UTC

    Please show your code, and the undesirable output it gave. You might be close !

    The way forward always starts with a minimal test.
Re: Search hash keys using values from array
by BillKSmith (Monsignor) on Mar 23, 2017 at 14:25 UTC
    Consider using a module to reverse the hash. Perhaps the function safe_reverse from Hash::MoreUtils.
    Bill
Re: Search hash keys using values from array
by tybalt89 (Monsignor) on Mar 23, 2017 at 22:14 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1185598 use strict; use warnings; my @array = qw(world today is very nice); my %hash = (0 => "Hello", 1=> "world" , 2=> "today" , 3=> "is" , 4=> " +nice", 5=> "is"); my %reversehash; # allow for different keys mapping to the same value push @{ $reversehash{$hash{$_}} }, $_ for keys %hash; my @newarray = map @{ $reversehash{$_} // [] }, @array; use Data::Dumper; print Dumper \@newarray;