Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Using an element in a Hash of Arrays to access the key

by tybalt89 (Monsignor)
on Mar 25, 2017 at 17:34 UTC ( [id://1185931]=note: print w/replies, xml ) Need Help??


in reply to Using an element in a Hash of Arrays to access the key

#!/usr/bin/perl # http://perlmonks.org/?node_id=1185923 use strict; use warnings; my @array1 = ("one", "two", "three", "four", "five"); my @array2 = ("banana", "pear", "apple"); my %hash = ( numbers => \@array1, fruit => \@array2 ); # make a reverse lookup hash my %reverse; for my $key (keys %hash) { push @{ $reverse{$_} }, $key for @{ $hash{$key} }; } # then do direct lookup ( you may get multiple values, or none ) print "banana -> @{ $reverse{'banana'} // [] }\n";

Replies are listed 'Best First'.
Re^2: Using an element in a Hash of Arrays to access the key
by orangepeel1 (Novice) on Mar 25, 2017 at 17:45 UTC
    Thank you, this worked. Could you clarify what the purpose of  // [] is in  print "banana -> @{ $reverse{'banana'} // [] }\n";?

      That is there to handle the case when the element you are trying to look up does not exist.
      Try looking up 'peach' with and without that part of the code.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1185931]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-24 06:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found